YAPTCHA
The math department has been having problems lately. Due to immense amount of unsolicited automated programs which were crawling across their pages, they decided to put Yet-Another-Public-Turing-Test-to-Tell-Computers-and-Humans-Apart on their webpages. In short, to get access to their scientific papers, one have to prove yourself eligible and worthy, i.e. solve a mathematic riddle.
However, the test turned out difficult for some math PhD students and even for some professors. Therefore, the math department wants to write a helper program which solves this task (it is not irrational, as they are going to make money on selling the program).
The task that is presented to anyone visiting the start page of the math department is as follows: given a natural n, compute
where [x] denotes the largest integer not greater than x.
Input
The first line contains the number of queries t (t <= 10^6). Each query consist of one natural number n (1 <= n <= 10^6).
Output
For each n given in the input output the value of Sn.
Sample Input
13
1
2
3
4
5
6
7
8
9
10
100
1000
10000
Sample Output
0
1
1
2
2
2
2
3
3
4
28
207
1609
思路:
本题就是威尔逊定理的应用,如果3K+7是素数,那么(3K+6)!+1就可以整除3K+7了。这样的话括号内表达式的结果就是1,否则括号内的表达式的结果就是0。首先采用筛选法筛出3000010以内的素数。然后开一个数组记录每个n下的输出值。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int p[3000010],a[1000010];//素数数组,结果保存数组
const int T=3000010;
void prime()//筛选法求素数
{
p[1]=1;
for(int i=4;i<=T;i+=2)p[i]=1;//将偶数全部标记,否则会筛不完全。
for(int i=3;i<=sqrt(T);i+=2)
{
if(!p[i])
{
for(int j=i+i;j<=T;j+=i)p[j]=1;
}
}
}
void sum()
{
for(int j=2;j<=1000000;j++)
{
if(!p[j*3+7])a[j]=a[j-1]+1;//该数是素数,对应结果为上一个数结果加一
else a[j]=a[j-1];//否则就是加0
}
}
int main()
{
prime();
sum();
int n;
cin>>n;
while(n--)
{
int t;
cin>>t;
cout<<a[t]<<endl;//直接输出结果
}
return 0;
}
第一次运用威尔逊定理,感谢大佬博客给与的参考:点击这里