import java.io.IOException;
import java.util.Scanner;

public class Sieve {
	static Scanner cin = new Scanner(System.in);

	public static void main(String[] args) {
		// We will compute all primes less than the value specified on the
		// command line, or, if no argument, all primes less than 100.
		int max = 100;// assign a default value
		
		if (cin.hasNext())
			max = cin.nextInt();
		// 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 < max; ++i)
			isprime[i] = true;
		// However,we know that 0 and 1 are not primes.Make a note of it.
		isprime[0] = isprime[1] = false;
		// Make sure n less than the square root of max can reduce the loop times.
		int n = (int) Math.ceil(Math.sqrt(max));
		for (int i = 2; i <= n; ++i) {
			if (isprime[i]) {
				for (int j = 2 * i; j <= max; j += i)
					isprime[j] = false;	// j=x*i,so they are not prime.
			}
		}
		int largest;
		// Now go look for the largest prime.
		for (largest = max; !isprime[largest]; --largest)
			;
		// output the result.
		System.out.println("The largest prime less than or equal to " + max
				+ " is " + largest);
	}
}

posted on 2011-10-06 20:55  Mathida  阅读(250)  评论(0)    收藏  举报