Question: public class Lab2 { public static boolean isPrime(int n) { int root = (int) Math.sqrt(n); for (int i=2; i

public class Lab2

{

public static boolean isPrime(int n)

{

int root = (int) Math.sqrt(n);

for (int i=2; i<=root; i++)

{

if ((n%i) == 0)

{

return false;

}

}

return true;

}

public static boolean isPrime(int n, int[] primes) {

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[])

{

int primes[];

primes = new int[1000000];

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, primes))

{

c++;

}

}

end = System.currentTimeMillis();

mstime = end - start;

System.out.println("#primes(prime method) = " + c + ", mstime = " + mstime);

}

}

This is the code I have so far. it is still wrong. I need to figure out how to figure out the prime numbers between 2 and the square root of the number. I was told that I need to figure out how to devide 'n' by every PRIME number between 2 and sqrt(n). All the dividing should take place in the isPrime method.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!