Prime number program does not work - java

I am trying to make a simple program in Java that would output all the prime numbers (skipping number 2) up to the number n. It doesn't work and I am out of ideas. If someone could take a look at my code and tell me what the problem is I would greatly appreciate it.
public class PrimeNum {
public static void main(String[] args) {
int n = 50;
int notAPrime = 0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i = n; i > 2; i--){
for(int j = 2; j < i; j++){
if(i % j == 0){
notAPrime++;
}
}
if(notAPrime == 0){
System.out.println(i);
notAPrime = 0;
}
}
}
}

Just declare notAPrime inside for(int i = n; i > 2; i--) to make it local for each i - candidate to be prime.
Now you increase notAPrime and never reset it to zero.

try this
public class primeNum {
public static void main(String[] args) {
int n = 50;
boolean prime;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i = n; i > 2; i--){
prime = true;
for(int j = 2; j < i; j++){
if(i % j == 0){
prime = false;
}
}
if(prime){
System.out.println(i);
}
}
}
}
note, that i changed your "notAPrime" variable from int into boolean and into a name that tells you what it means. if you only increment the "notAPrime" integer, you will never get any desired outcome.
By the way, this wa a hotfix and you got a corrected first form of your code. Have in mind, that 2 is a prime number aswell and your code ignores this.
Just work a little mor on it ;)

You are missing a "break" in your for loop.
public class primeNum {
public static void main(String[] args) {
int n=50;
int notAPrime=0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i=n; i>2; i--){
for(int j=2; j<i; j++){
if(i%j==0){
notAPrime++;
break; //your program is missing this statement
}
}
if(notAPrime==0){
System.out.print(i + " ");
}
notAPrime=0; //In your program it is inside the if statement which makes it incorrect.
}
}
}
Output:
All prime numbers before number 50 are :
47 43 41 37 31 29 23 19 17 13 11 7 5 3
You can make your program more efficient by making the following changes:
public class primeNum {
public static void main(String[] args) {
int n=50;
int notAPrime=0;
System.out.println("All prime numbers before number " +n+ " are : ");
for(int i=n; i>2; i--){
if(i%2==0){
continue;
}
for(int j=3; j<i; j+=2){
if(i%j==0){
notAPrime++;
break;
}
}
if(notAPrime==0){
System.out.print(i + " ");
}
notAPrime=0;
}
}
}

Related

Changing the return type and also the last number to be printed

I have the below java program which prints all the prime numbers till 100, now I want to modify the same so that user will enter the number and it will print not the range but the very last prime number exists in that range, please advise how to modify the below program also I want to change the return type from string to int that is                     
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
right now the output is
Prime numbers from 1 to 100 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
and I want only last prime number to be printed only
100
Try just maintaining state for the most recent prime number discovered by the loop:
public static void main (String[] args) {
int i = 0;
int num = 0;
int prime;
for (i = 1; i <= 100; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
prime = i;
}
}
System.out.println("Last prime number from 1 to 100 is: " + prime);
}
The proposed source codes can be written more structured:
public class PrimeNumbers {
private static boolean isPrime(int n) {
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= Math.sqrt(n); i = i + 2)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
int biggestPrimeNumber = 0;
String primeNumbers = "";
for (int n = 2; n <= 100; n++)
if (isPrime(n)) {
biggestPrimeNumber = n;
//Appended the Prime number to the String
primeNumbers += n + " ";
}
System.out.println("Prime numbers from 1 to 100 are: " + primeNumbers);
System.out.println("Last prime number from 1 to 100 is: " + biggestPrimeNumber);
}
}
For checking the primality of a number there are many algorithms like Miller–Rabin primality test but a simple brute force way is to check numbers up to sqrt of the desired number.
You might want to introduce a int variable (int primeNumber) that will hold the value of the largest prime number. Made some minor changes in problem code:
int i = 0;
int num = 0;
//Empty String
int primeNumber = 0;
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i%num==0) {
counter = counter + 1;
}
}
if (counter ==2) {
primeNumber = i;
}
}
System.out.println("Largest Prime number from 1 to 100 is : ");
System.out.println(primeNumber);
As per my understanding ,you want to print the max prime number which is closed to 100.
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
for (i = 1; i <= 100; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = i+ "";
}
}
System.out.println("Max prime number between 1 to 100 is:");
System.out.println(primeNumbers);
}
}
UPDATE :
This program can be further optimized to improvise time complexity
public class PrimeNumbers{
public static void main (String[] args)
{
int i =0;
int num =0;
int primeNumbers = 0;
for (i = 100; i >= 1; i--)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
primeNumbers = i;
break;
}
}
System.out.println("Max prime number between 1 to 100 is:");
System.out.println(primeNumbers);
}
}

Why is this if-condition always excluding 2?

I created this loop to find prime numbers, the int num is initialized as 0, but the debugger always skips 1 (which is correct) and 2 (which is not correct).
How does it come that it always skips 2 % 2 == 0 ?
for (int num = 0; num <= 100; num++) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
System.out.println(num + " is not a prime number.");
break;
}
if (num - j == 1) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}
The problem with your code is that in the case num=2 you don't get into the part where you add the prime number. You chose to use the last iteration of the inner loop as the place where to add a prime number to your list, but with num=2 the inner loop has 0 iterations.
I'd modify your program as follows:
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static boolean isPrime(int num) {
for (int j = 2; j < num; j++) {
if (num % j == 0) {
return false;
}
}
return true;
}
public static void main (String [] args) {
List<Integer> myPrimeNumbers = new ArrayList<>();
for (int num = 2; num <= 100; num++) {
if (isPrime(num)) {
System.out.println("PRIME NUMBER FOUND! It's: " + num + ".");
myPrimeNumbers.add(num);
}
}
}
}
Extracting the prime test into a method makes it easy to place the true and false returns at locations where they are intuitively correct.
And I started the prime number search with 2 instead of 0 as we all know that 0 and 1 are by definition no primes.

Java - vertical integers and palindrome

I stumbled upon an exercise that asked me to reproduce this (that's the expected output):
11111
3456789012109876543
This is a palindrome (at the bottom) where numbers higher that 9 (double digits) have to be written vertical. This sounds complicated to me, and I needed some help.
This is what I did so far, the palindrome:
class Print {
public static void main(String[] args) {
System.out.println("Insert a number from 1 to 100: ");
int input = Read.anInt();
System.out.println("Insert another number from 1 to 100: ");
int output = Read.anInt();
int a = input;
for (int i = a; i < output; i++){
System.out.print(a);
a++;
}
a = input -1;
for (int j = output; j > a; j--){
System.out.print(output);
output--;
}
}
}
Could you help me by explaining how to make sure numbers higher than 9 will be written vertically?
AdamRice: i mean this:
3456789111119876543
01210
But what I've managed to do so far is this mess:
456789101
0
111
1
121110987654
This is all probably because I'm completely ignoring arrays.
Apologies for being a bit slow. After finally understanding the problem, I think I have a solution.
import java.util.Scanner;
public class VerticalText {
public static void main(String[] args) {
Scanner Read = new Scanner(System.in);
System.out.println("Insert a number from 1 to 100: ");
int start = Read.nextInt();
System.out.println("Insert another number from 1 to 100: ");
int end = Read.nextInt();
String numbers = "";
for(int i = start; i <= end; i++)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
for(int i = (end-1); i >= start; i--)
{
if(i < 10)
{
numbers += String.format("%02d", i);
}
else
{
numbers += i;
}
}
String row1 = "";
String row2 = "";
char[] chars = numbers.toCharArray();
for(int i = 0; i < chars.length; i++)
{
if(chars[i] == '0')
{
chars[i] = ' ';
}
row1 += chars[i];
i++;
row2 += chars[i];
}
System.out.println(row1);
System.out.println(row2);
}
}
With inputs 5 and 15, it produced the following output:
11111111111
567890123454321098765
Explanation
I build a string of the numbers and if it's less than 10 format it with a leading 0. This extra 0 is just a placeholder. When it comes to printing, we can print a space instead of a zero.

What is causing my infinite loop?

I can't seem to figure out what I did wrong with my code to create an infinite loop. I would really appreciate it if someone could help explain this to me.
import java.util.Scanner;
class LoopMath1 {
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner(System.in);
//gets a number from a user and parses the string as an int
System.out.println("Please give me a positive number");
String userNum;
userNum = inputScanner.nextLine();
System.out.println("Your number is " + userNum + ".");
int number = Integer.parseInt(userNum);
printX(number); //function call
//prints 2 to the x power
System.out.print("2^" + number + "=");
int j = 1;
int twoToThe = 2;
while (j < number) {
twoToThe *= 2;
j++;
}
System.out.print(twoToThe);
//determines if the user number is prime
int i = 0;
for (i = 1; 1 < number; i++) {
int nPrime = number;
if (nPrime == 0) {
System.out.println(number + " is not prime.");
break;
} else {
System.out.println(number + " is prime.");
}
}
}
//this is a function to print a certain amount of Xs, depending on the user input
public static void printX(int nTimes) {
final int WIDTH = nTimes;
while (nTimes < WIDTH) {
System.out.print("x");
nTimes += 1;
}
}
}
for (i=1; 1 < number; i++) has a typo. 1 should be i as in for (i=1; i < number; i++)
Replace
for (i=1; 1 < number; i++) {
by
for (i=1; i < number; i++) {
Your incrementor initialized in the first part of your for loop must be tested in the second part preferably and incremented in the third one.

Java output in lines of ten

I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}

Categories