FileDocCategorySizeDatePackage
Sieve.javaAPI DocExample1283Sat Jun 02 02:43:44 BST 2001None

Sieve.java

// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

/**
 * This program computes prime numbers using the Sieve of Eratosthenes
 * algorithm: rule out multiples of all lower prime numbers, and anything
 * remaining is a prime.  It prints out the largest prime number less than
 * or equal to the supplied command-line argument
 **/
public class Sieve {
  public static void main(String[] args) {
    // We will compute all primes less than the supplied command line argument
    // Or, if no argument, all primes less than 100
    int max = 100;                           // Assign a default value
    try { max = Integer.parseInt(args[0]); } // Try to parse user-supplied arg
    catch (Exception e) {}                   // Silently ignore exceptions.

    // Create an array that specifies whether each number is prime or not.
    boolean[] isprime = new boolean[max+1];

    // Assume that all numbers are primes, until proven otherwise.
    for(int i = 0; i