Question: I need help altering my code using brute force for java, The goal is to count and print prime numbers from 1 to 1000000 These

I need help altering my code using brute force for java,

The goal is to count and print prime numbers from 1 to 1000000

These are the tips we were given

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. For lab2, you will implement a solution to #3 above. Improve upon the program that I gave you in class so that it will only test the PRIME numbers between 2 and the square root of 'n' when it is testing a given number 'n' for prime. 

public class PrimeNumb {

public static boolean isPrime(int n) { int lim = (int) Math.sqrt(n);

if (n <= 1) { return false; } if (n <= 2) { return true; }

for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } public static void main(String args[]) { int c=0; long start, end, mstime; for (int i = 0; i<= 1000000; i++)

for (int n = 3; n<=1000000; n++)

if (isPrime(n)) {

final int LIMIT=1000000; // 1M took ~800 secs.

start = System.currentTimeMillis();

prime = new int[LIMIT/10]; prime[0] =2; //primes is a local variable and has scope of the array, second half ok

for (int i=2; i

if (isPrime(i)) { System.out.println(i);

c++; } }

end = System.currentTimeMillis();

mstime = end - start;

System.out.println("#primes = " + c + ", mstime = " + mstime); } start = System.currentTimeMillis();

prime = new int[LIMIT/10]; prime[0] =2; //primes is a local variable and has scope of the array, second half ok

for (int i=2; i

if (isPrime(i)) { System.out.println(i); c++; } }

end = System.currentTimeMillis();

mstime = end - start;

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

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!