求质数…

import java.text.DecimalFormat;
import java.util.*;

public class Lab12Extended {
    static int MAX;
    public static void main(String args[]) {
        // This main method needs additions for the 100 point version.
        System.out.println("nThe "Sieve of Eratosthenes"n");
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the primes upper bound ===> ");
        MAX=input.nextInt();
        boolean primes[];
        primes = new boolean[MAX+1];
        Arrays.fill(primes, true);
        primes[1]=false;
        computePrimes(primes);
        displayPrimes(primes);
    }

    public static void computePrimes(boolean primes[]) {
        int count;
        int test;
        int temp;
        System.out.println("nComputing Prime Number n");
         for (count=2;count<=MAX;count++){
             for (test=2;test<=MAX;test++){
                 if (count!=test){
                     temp=count%test;
                     if (temp==0){
                         primes[count]=false;
                     }
                 }
             }
         }
    }

    public static void displayPrimes(boolean primes[]) {
        System.out.println("Primes between 1 and "+MAX+"n");
        int count;
            DecimalFormat df = new DecimalFormat("000");
            for (count=2;count<=MAX;count++){
                if (primes[count]==true){
                    System.out.print(df.format(count)+" ");
                }
            }
    }
}

Animation_Sieve_of_Eratosth-2

Posted in Java. 标签:, . No Comments »