08 Homework Project.docx

advertisement
Week 8 Homework Project
You are to write a program to calculate prime numbers using an array.
I suggest you begin with the Test3.java as a starting point.
The first input field should ask the user: “How many primes?”
The second input field should ask the user: “Which prime?”
Your program will allocate an array to store primes, its size based on the first input. Name the array
“primes”.
Then your program will fill the array with prime numbers: primes[0]=2, primes[1]=3, …
You may find it useful to Google “Sieve of Erasthones”
Having a list of existing primes is important for calculating new ones. So your program will both put
numbers in the array, and use numbers in the array to calculate new primes.
Remember, the “%” operator in Java is very useful in determining whether a given number is divisible by
another. If ( (a % b) ==0), then a is divisible by b.
Hint: You may find it useful to initialize the array of primes with one or two primes. You may find it
useful to construct a ‘for’ loop with a counter that checks candidates (numbers that might be prime),
but not use the loop counter in the part of the ‘for’ statement that checks for the end of the loop.
Extra credit: Use the fact that the inner loop need not test any primes bigger than the square root of the
candidate, to make the program work slightly faster. Do this without using any square root function. If
you do this, explain in your comments what you are doing and why.
Turn in the project in the drop box by midnight on Tuesday, March 3rd.
Download