Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java2 Lab2 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

Java2 Lab2 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. 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. NOTE: If you add any extra "initialization" methods to your program, make sure and include their call inside the two calls to currentTimeMillis() Name your ~/PF2/lab2/Lab2.java.

This is what I have so far, I am having trouble with the boolean since we have to make each number divide by the square root of all the numbers from 2 to 1M.

public class Lab2 {

public static boolean isPrime(int n){

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

int primes[]; primes = new int[1000000];

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

if ((n%Math.sqrt(n))== 0) {

return false;

} }

return true; }

public static void main(String args[]) {

int c=0;

long start, end, mstime;

final int LIMIT = 1000000;

start = System.currentTimeMillis();

for (int i=0;

long start, end, mstime;

final int LIMIT = 1000000;

start = System.currentTimeMillis();

for (int i=0; i

end = System.currentTimeMillis();

mstime = end - start;

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

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

Step: 3

blur-text-image

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

Database Design Application Development And Administration

Authors: Michael V. Mannino

4th Edition

0615231047, 978-0615231044

More Books

Students also viewed these Databases questions