LightOJ - 1259 Goldbach`s Conjecture【素数筛+枚举】
2017-08-15 10:33
225 查看
Goldbach`s Conjecture
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].
Now your task is to check whether this conjecture holds for integers up to 107.
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 ≤ 107, 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
1) Both a and b are prime
2) a + b = n
3) a ≤ b
Sample Input
2
6
4
Sample Output
Case 1: 1
Case 2: 1
Hint
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, ...
可以先用素数筛筛出1e7以内的素数,标记并存起来。显然在这里1e6都存的下,如果直接开1e7的话会内存超限。枚举的时候也有一些小技巧。可以枚举<=n/2以内的素数,然后判断n-prime[i]是否为素数就好了,这样不会超时。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX_N 10000000
int prime[MAX_N/10];
bool is_prime[MAX_N+1];
void sieve(int n)
{
int p = 0;
memset(is_prime,true,sizeof(is_prime));
is_prime[0] = is_prime[1] = false;
for(int i = 2; i <= n/2; i++)
{
if(is_prime[i])
prime[p++] = i;
for(int j=0; j<p && prime[j]*i<=n; j++)
{
is_prime[prime[j]*i]=false;
if(i%prime[j]==0)
break;
}
}
// for(int i=0;i<10000;i++)
// printf("%d ",prime[i]);
}
int main()
{
int t;
sieve(MAX_N);
scanf("%d",&t);
for(int tt=1; tt<=t; tt++)
{
int n,sum=0;
scanf("%d",&n);
for(int i=0;prime[i]<=n/2;i++)
{
if(is_prime[n-prime[i]])
sum++;
}
printf("Case %d: %d\n",tt,sum);
}
return 0;
}
相关文章推荐
- LightOJ 1372 (枚举 + 树状数组)
- LightOJ 1156 - Jumping Frogs 二分枚举 + 最大流
- LightOJ-1341 Aladdin and the Flying Carpet 分解质因数(注意对大素数的优化)
- LightOJ-1259 Goldbach`s Conjecture 数论 素数筛
- LightOJ - 1370 Bi-shoe and Phi-shoe (欧拉函数,素数打表)
- lightoj 1235 Coin Change (IV)(折半枚举)
- HDU 6069 Counting Divisors(枚举区间)(素数筛模版)
- kuangbin专题十四 LightOJ1259 素数筛
- LightOJ 1236 Pairs Forming LCM(唯一分解定理+素数刷选)
- LightOJ 1235 - Coin Change (IV) (折半枚举)
- LightOJ 1197 Help Hanzo (区间素数筛选法)
- Lightoj 1100 - Again Array Queries (枚举剪枝)
- poj2262 Goldbach's Conjecture(线性素数筛+暴力枚举)
- LightOJ 1370 Bi-shoe and Phi-shoe(素数)
- LightOJ 1197 Help Hanzo(区间素数筛选)
- LightOJ 1370 Bi-shoe and Phi-shoe(素数筛)
- LightOJ 1356 Prime Independence (素数 二分图)
- HDU 5778 (压缩范围枚举暴力跑素数表)
- LightOJ 1220 Mysterious Bacteria(唯一分解定理 + 素数筛选)
- POJ 2739 Sum of Consecutive Prime Numbers 暴力枚举+素数判断