另类打表:将从1到n的满足美素数条件的数目赋值给prime[n],这样最后只需要用prime[L]减去prime[R-1]即可;
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 2332 Accepted Submission(s): 811
3 1 100 2 2 3 19
Case #1: 14 Case #2: 1 Case #3: 4
代码:
#include<stdio.h> #include<string.h> #define MAXN 1000005 int pri[MAXN] = {1,1}; int prime[MAXN]; int mei( int n ) { int i, sum = 0, pre = n; while(n){ sum += n%10; n/=10; } if( pri[sum] == 0 ) return 1; else return 0; } void f() { for( int i = 2, k = 0; i < MAXN; i ++ ){ if( pri[i] == 0 ){ if( mei(i) ) ++k; for( int j = i+i; j < MAXN; j += i ) pri[j] = 1; } prime[i] = k; } } int main() { int l, r, t, ans, v = 1; scanf("%d", &t ); f(); while( t -- ){ scanf( "%d%d", &l, &r ); printf( "Case #%d: ", v++ ); printf( "%d\n", prime[r]-prime[l-1] ); } return 0; }
原文地址:http://blog.csdn.net/shengweisong/article/details/38065573