Question: I have been working on this for a while now and cant seem to figure it out. Write a program that will calculate all of
I have been working on this for a while now and cant seem to figure it out.
Write a program that will calculate all of the prime numbers less than 1,000,000. Also, determine how many primes there are less than 1,000,000. There are many different ways to tackle this problem, some more efficient than others. Most "simple" methods for determining whether a number of primes do so by searching for factors. Actually, the question of determining if a number is prime _can_ be answered without ever actually finding any factors of a non-prime (composite) number are! But for this lab, we'll just stick with the relatively simple approach of searching and testing possible factors through BRUTE FORCE and trial and error. Several methods, each slightly "better" than the one before: 1) Test every value between 2 & the number. 2) Test every value between 2 and the square root of the number. 3) Test only the prime numbers between 2 and the square root of the number.
This is what I have so far, which I thought was right and done.
public class Lab2b
{
public static int[] primes = null;
public static boolean isPrime(int n)
{
if(primes[0] == 0)
{
int root = (int) Math.sqrt(n);
for (int i=2; i<=root; i++)
{
if ((n%i) == 0)
{
return false;
}
}
return true;
}
else
{
int root = (int) Math.sqrt(n);
int i = 2;
int index = 0;
while(i<=root) {
if ((n%i) == 0)
{
return false;
}
i = primes[index];
index++;
}
return true;
}
}
public static void main(String args[])
{
primes = new int[1000000];
//Set all of them to 0
for(int i = 0; i < 1000000; i++) {
primes[i] = 0;
}
int c=0;
long start, end, mstime;
final int LIMIT=1000000; // 1M took ~800 secs.
start = System.currentTimeMillis();
for (int n=1; n<=LIMIT; n++)
{
if (isPrime(n))
{
System.out.println(n);
primes[c] = n;
c++;
}
}
end = System.currentTimeMillis();
mstime = end - start;
System.out.println("#primes = " + c + ", mstime = " + mstime);
c = 0;
start = System.currentTimeMillis();
for (int n=1; n<=LIMIT; n++)
{
if (isPrime(n))
{
c++;
}
}
end = System.currentTimeMillis();
mstime = end - start;
System.out.println("#primes(prime method) = " + c + ", mstime = " + mstime);
}
}
When I asked to check my program, this is what the instructor told me. "In your isPrime method, if you look at the code that does the division: if ((n%i) == 0) . Note that you are dividing by 'i' . You need to divide by an element from your primes array! Also note that your program, as written, only finds three prime numbers!"
I am lost, tired, and frustrated if anyone could help. Please and Thank you.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
