Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Records And Database Management

Authors: Jeffrey R Stewart Ed D, Judith S Greene, Judith A Hickey

4th Edition

0070614741, 9780070614741

More Books

Students also viewed these Databases questions

Question

What are the types of forms of communication ?

Answered: 1 week ago

Question

Explain the process of MBO

Answered: 1 week ago