欧拉筛(素数筛)

欧拉筛:利用每个最小质因子筛掉合数,并且不会重复筛到。

题:
Goldbach’s conjecture is one of the oldest unsolved problems in number theory and in all of mathematics. It states:

Every even integer, greater than 2, can be expressed as the sum of two primes [1].

Your task is to check whether this conjecture holds for integers up to 10^7.

Input
Input starts with an integer T (≤ 300), denoting the number of test cases.

Each case starts with a line containing an integer n (4 ≤ n ≤ 10^7, n is even).

Output
For each case, print the case number and the number of ways you can express n as sum of two primes. To be more specific, we want to find the number of (a, b) where:

Both a and b are prime,
a + b = n and
a ≤ b.

Sample Input
2
6
4

Sample Output
Case 1: 1
Case 2: 1

Note
[1] An integer is said to be prime, if it is divisible by exactly two different integers. First few primes are {2, 3, 5, 7, 11, 13, …}.

题意:
测试样例t。
输入整数n。
条件:a+b=n并且a<=b并且a、b都是素数。
找出有多少个这样的成立。

#include<iostream>
using namespace std;

const int maxn = 7e6;
const int N=1e7+5;
long prime[maxn],countnum =0;	//prime数组记录素数,countnum记录素数个数 
bool p[N]={false};

void isprime()	//查找记录2到n的素数 
{
	long long i,j;
	for(i=2;i<=N;++i)
	{
		if(p[i]==false)	//如果未被筛过,则为素数 
			prime[countnum++]=i;
		for(j=0;j<countnum;++j)
		{
			if(i*prime[j]>N)	//当要标记的合数超出范围时跳出 
				break;
				
			p[i*prime[j]]=true;	//将已经记录的素数的倍数进行标记 
			
			if(i%prime[j]==0)	
				break; 
				
			//当i是prime[j]的整数倍时
			//记 m = i / prime[j]
			//那么 i * prime[j+1] 就可以变为 (m * prime[j+1]) * prime[j]
			//这说明 i * prime[j+1] 是 prime[j] 的整数倍
			//不需要再进行标记(在之后会被 prime[j] * 某个数 标记)
			//对于 prime[j+2] 及之后的素数同理,直接跳出循环,这样就避免了重复标记。
		}
	}
}

int main()
{
	int t,o=0;
	cin>>t;
	isprime();
	while(t--)
	{
		o++;
		long long n,s=0;
		cin>>n;
		for(int i=0;prime[i]<=n/2;++i)
		{
			if(p[n-prime[i]]==false)
			{
				s++;
			}
		}
		cout<<"Case "<<o<<": "<<s<<endl;
	}
	return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值