筛法+前缀和

A pretty straight forward task, calculate the number of primes between 2 integers.

Given 2 integers A ≤ B < 10
5 what’s the number of primes in range from A to B inclusive.

Note: A prime number is a positive integer greater than 1 and is divisible by 1 and itself only. For N to be prime it is enough to test the divisibility of numbers less than or equal to square root of N.

    Input
    
  
   As many as 1000 lines, each line contains 2 integers A and B separated by a space. Input is terminated when A = B = -1 (Do not process this line).
  

    Output
    
  
   For every line in input – except for the last line where A = B = -1 - print the number of prime numbers between A and B inclusive.
  

    Sample Input
    0 9999

1 5
-1 -1

    Sample Output
    1229

3

#include<iostream>
#include<algorithm>
using namespace std;

const int N=100010;

int st[N];

int main()
{
	for(int i=2;i<N;i++)
	{
		if(!st[i])
		{
			for(int j=i+i;j<N;j+=i)
				st[j]=1;
		}
	}

st[0]=0;
	st[1]=0;
	for(int i=2;i<N;i++)
	{
		if(st[i]==0) st[i]=1;
		else st[i]=0;

	st[i]+=st[i-1];
	}

int a,b;
	while(cin>>a>>b)
	{
		if(a==-1&&b==-1)break;
		
		cout<<st[b]-st[a-1]<<endl;
	}
}

发布了29 篇原创文章 · 获赞 24 · 访问量 3687

猜你喜欢

转载自blog.csdn.net/qq_45772483/article/details/104249669