r/javahelp • • Mar 12 '15

Prime Calculator Program (Help!)

This program is supposed to calculate a prime number, add it to the prime list, and use it again to find more primes by the remainder. For some reason it doesn't calculate the right number of primes and shows numbers that are not prime. I sort of did trial and error but I keep failing. Please Help!

import java.util.Scanner;


public class PrimeCalc{

	public static void main(String[] args) {
		/*
		 * This program finds a number of primes defined by the user in order.
		 * uses primes added to the list to calculate new primes
		 */
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the number of prime numbers you want to find");
		int numOfPrimes = input.nextInt();
		int[] primes = new int[numOfPrimes];
		int[] primeslist = new int[numOfPrimes];
		int count = 0;
		int temp = 2;
		
		System.out.println("The list of primes:");
		System.out.println("2");
		for (int k = 0; k < numOfPrimes; k++){
			primeslist[k] = 2;
			for (int j = 0; j <= k; j++){
				if (temp % primeslist[j] != 0){
					primes[k] = temp;
					System.out.println(primes[k]);
					count++;
					j = k+1;
				}
			}
			temp++;
		}
	}
}
3 Upvotes

6 comments sorted by

View all comments

1

u/viciu88 Intermediate Brewer Mar 12 '15

fixed your checking is temp is prime

boolean isPrime = true; //assuming temp is a prime
for (int j = 0; j <= k && isPrime; j++) //for each already found prime
    if (temp % primeslist[j] == 0) //if primelist[j] is divisor of temp
		isPrime = false; //then its not a prime

if(isPrime)
{//we checked all and it's still a prime
	primes[k] = temp;
    System.out.println(primes[k]);
	count++;
}