Prime.java

package com.bozoid.cis370.hw01.simple;

/**
Generate the first <code>n</code> prime numbers.

@author Walt Leipold
@version 1.0
*/
public class Prime
{
    /**
    Invoke this function from the command line with one argument, 
    <code>n</code>, the number of primes to generate.
    */
    public static void main(String argv[])
    {
        int i;
        String ordinals[] = {"zeroth","first","second","third"};

        if (argv.length != 1) {
            System.err.println(
                "Usage: Prime <number of primes to print>");
            System.exit(2);
            }
        int nprimes = Integer.parseInt(argv[0]);
        if (nprimes <= 0)
            nprimes = 1;

        int primes[] = new int[nprimes];
        primes[0] = 2;

        int primecount = 1;
        int test = 3;
        while (primecount < nprimes) {
            boolean foundFactor = false;
            for (i=0; i<primecount; i++)
                if (test % primes[i] == 0) {
                    foundFactor = true;
                    break;
                    }
            if (!foundFactor)
                primes[primecount++] = test;
            test += 2;
            }

        // Print primes. If more than 10, print first 5 & last 5.
        if (nprimes <= 10)
            for (i=0; i<nprimes; i++)
                System.out.println("   " + primes[i]);
        else {
            for (i=0; i<5; i++)
                System.out.println("   " + primes[i]);
            System.out.println("   ...");
            for (i=nprimes-5; i<nprimes; i++)
                System.out.println("   " + primes[i]);
            }

        // Print summary.
        if (nprimes <= 3)
            System.out.println("The " + ordinals[nprimes] + 
                " prime number is " + primes[nprimes-1]);
        else
            System.out.println("The " + nprimes + "th" +
                " prime number is " + primes[nprimes-1]);
    }
}