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

2

u/somnolent Mar 12 '15

Well, you're getting bad primes because you aren't requiring that the potential prime isn't divisible by all prior primes, you're only requiring that it isn't divisible by one of them. In your case, you end up with a bunch of odd numbers in your primes list because they aren't divisible by your first prime (2) and you treat them as a prime.

The reason you're getting weird counts back is that you're looping from k to numOfPrimes, but what happens if k isn't a prime? You never get a chance to fill in that spot of the array again. You need to separately track your potential prime vs your array location.