题目:给你一个数,问有多少对素数的和小于这个数。
分析:数论。利用素数表枚举求解。
1.打表计算1000000内的素数(筛法);
2.对于每个输入的数字 v,枚举他的所有拆分情况;
设F(i)是不超过数字 i 的素数的个数,S(v)为 v 的拆分种数,则:
S(v)= sum(min(F(i),v - F(i)+ 1 )) { 1 < i < v }
说明:算了一下最坏情况会超时(600组都是1000000),结果跑了198ms (⊙_⊙)
#include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #define min(a,b) (a)<(b)?(a):(b) using namespace std; int visit[1000001]; int prime[1000001]; int F[1000001]; int bs( int r, int key ) { int mid,l = 0; while ( l < r ) { mid = l+(r-l+1)/2; if ( prime[mid] >= key ) r = mid-1; else l = mid; } return l; } int main() { int count = 1; for ( int i = 0 ; i < 1000001 ; ++ i ) visit[i] = F[i] = 0; prime[0] = 0; for ( int i = 2 ; i < 1000001 ; ++ i ) if ( !visit[i] ) { prime[count ++] = i; for ( int j = i*2 ; j < 1000001 ; j += i ) visit[j] = 1; } int value,sum,T = 1; while ( scanf("%d",&value) && value ) { sum = 0; for ( int i = 2 ; prime[i] < value ; ++ i ) sum += bs( count-1, min( prime[i], value-prime[i]+1 ) ); printf("Case %d: %d\n",T ++,sum); } return 0; }
UVa 10742 - The New Rule in Euphomia,布布扣,bubuko.com
UVa 10742 - The New Rule in Euphomia
原文地址:http://blog.csdn.net/mobius_strip/article/details/38190277