How many primes

How many primes

Time Limit:1000MS  Memory Limit:65536K
Total Submit:396 Accepted:15

Description

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 5 is prime because 1 and 5 are its only positive integer factors, whereas 6 is composite because it has the divisors 2 and 3 in addition to 1 and 6. 
Prime looks so lonely because it only has a few factors. That is the reason Junko show special preference to the prime. Now, She wants to know how many primes in [l, r]. 

Input

Input contains multiple test cases. 
Each test case contains two integers l, r. (1 <= l <= r <= 1,000,000) 

Output

For each test case, Print a line, the numbers of prime in [l, r].

Sample Input

1 1
1 10
233 666

Sample Output

0
4
71

题意:求给定区间的质数数。

题解:先将1000000以内的质数筛一遍,然后用一个数组table记录质数个数。table[i]表示1-i的素数个数,那么当询问l-r区间的质数个数时,直接输出table[r]-table[l-1]即可。

//************************************************************************//
//*Author : Handsome How                                                 *//
//************************************************************************//
//#pragma comment(linker, "/STA	CK:1024000000,1024000000")
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <ctime>
//----------------------------------------------------------
const int maxn = 1000005;
int table[maxn];
bool p[maxn];
void init(){
	for(int i=0;i<maxn;i++)p[i]=true;
	p[0]=p[1]=false;
	for(int i=2;i<=1000000;i++){
		if(p[i]){
			for(int j = 2*i;j<=1000000;j+=i)p[j]=false;
		}
	}
	table[0]=table[1]=0;
	table[2]=1;
	for(int i=2;i<=1000000;i++)if(p[i])table[i]=table[i-1]+1;
	else table[i]=table[i-1];
}
int main()
{
	init();
	int l ,r;
	while(scanf("%d %d",&l,&r)!=EOF){
		printf("%d\n",table[r]-table[l-1]);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值