AOJ0009Prime Number

Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5, 7.

Input

Input consists of several datasets. Each dataset has an integer n (n ≤ 999999) in a line.

The number of datasets ≤ 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5

package 素數;

import java.util.Scanner;

public class AOJ0009_Prime_Number {

	/**
	 * @param args
	 */
	static int prime[] = new int[1000000];
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		getans();
		Scanner cin = new Scanner(System.in);
		while(cin.hasNext())
		{
			int a = cin.nextInt();
			System.out.println(prime[a]);
		}
	}
	private static void getans() {
		
		 //for(int i=0; i<1000000; i++)prime[i] = i;
		 prime[1] = 0;
		 prime[2] = 1;
		 for(int i=2; i<1000000; i++)
		 {
			 if(prime[i] == -1)
			 {
				 prime[i] = prime[i-1];continue;
			 }
			 prime[i] = prime[i-1] + 1;
			 for(int j=i*2; j<1000000; j+=i)
			 {
				 prime[j] = -1;
			 }
		 }
	}

}




發佈了77 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章