Re: Calculate primes help

I'm not sure what algorithm you have there, but the most efficient method to do this is by the Sieve of Eratosthenes.

You're getting the ArrayIndexOutOfBounds exception because you initialized primes[] to size 0, instead of to size x

Code :

System.out.println("Welcome to Prime Calculator!");
System.out.println("Enter a value: ");
x = stdin.nextInt();
primes = new int[x];

Re: Calculate primes help

I read a lot about that, and I feel like since we haven't learned about it, that's not what is expected in the program. My algorithm may not be the most efficient, but it seems like it should make sense? If the remainder of something divided by 2 = 0 then its not prime, if it is, try 3, if that is 0, then it's not prime, if it is, try 4, and so on..

Substituting x into the array got rid of the error message, but now onlys prints the number 2--sometimes once, sometimes twice, sometimes three times

Re: Calculate primes help

That's part of the fun of computer science: learning about new (well, in this case really old) algorithms that perform a given task.

The reason why you're algorithm isn't working is because you're checking the primality of x. If you want to go about it that way, I'd recommend writing a helper function that will check to see if a number is prime, then everytime you find a prime number, print it out.

Code :

for (int i = 2; i < x; i++)
{
if(isPrime(i))
{
System.out.println(i + " is prime");
}
}

A simple primality checker:

Code :

for every integer i from 2 to the number:
if the number is divisible by i, return not prime
end
return true

There are several optimizations that you can make, the biggest being that you only have to check numbers up to the square root of the number. The second is only to check to see if the number is divisible by 2, then return false. Then, only check to see if your number is divisible by odd numbers from 3 to sqrt(number)