Never
test for a bug you don't know how to fix.
- Mike McCracken
Answer the following questions. Bring hardcopies of your answers to class, hand written or printouts. All homeworks are due before class on the due date. Please remember that the UK Honor Code is in effect: Each student is expected to work alone and you may not share solutions or solution ideas.
Use the following main program for primes() for the questions below. The complete program primes.java is available for your reference.
// Finds and prints n prime integers
private static void printPrimes (int n)
{
int curPrime; // Value currently considered for primeness
int numPrimes; // Number of primes found so far.
boolean isPrime; // Is curPrime prime?
int [] primes = new int [MAXPRIMES]; // The list of prime numbers.
// Initialize 2 into the list of primes.
primes [0] = 2;
numPrimes = 1;
curPrime = 2;
while (numPrimes < n)
{
curPrime++; // next number to consider ...
isPrime = true;
for (int i = 0; i <= numPrimes-1; i++)
{ // for each previous prime.
if (isDivisible (primes[i], curPrime))
{ // Found a divisor, curPrime is not prime.
isPrime = false;
break; // out of loop through primes.
}
}
if (isPrime)
{ // save it!
primes[numPrimes] = curPrime;
numPrimes++;
}
} // End while
// Print all the primes out.
for (int i = 0; i <= numPrimes-1; i++)
{
System.out.println ("Prime: " + primes[i]);
}
} // end printPrimes
© Paul Ammann and Jeff Offutt, 2003, all rights reserved. This document is made available for use by GMU graduate students of SWE 637. Copying, distribution or other use of this document without express permission of the author is forbidden. You may create links to pages in this web site, but may not copy all or part of the text without permission of the author.