HDOJ 题目2973 YAPTCHA(数学,威尔逊定理)

YAPTCHA

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 584    Accepted Submission(s): 330


Problem Description
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
 

Source
Central European Programming Contest 2008
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   2970  2966  2967  2968  2969 
 思路:

这里需要应用素数判断的Wilson定理:

    p是素数  等价于   (p-1)! = -1 (mod p)

    显然,如果3k+7是素数,那么(3k+6)!+1必然能够被(3k+7)整除,此时,被减数为整数,整个项的值为1;由此定理的充要性也可知,当(3k+7)不为素数时,整个项的值为0,所以,Sn的值其实就是1到n之间素数的个数。

    考虑到问题数t较大,本题在初始化时可以使用筛选法先求出所有1到3000007之间的素数,然后对于每个n,计算出1到n之间的素数个数,存放在数组中。这样,每读入一个n,直接在数组中查找答案即可。

ac代码

#include
#include
#include
int a[1000010];
int pre(int n)
{
	int i;
	for(i=2;i<=sqrt(n);i++)
	{
		if(n%i==0)
			return 0;
	}
	return 1;
}
void fun()
{
	int i;
	a[0]=0;
	for(i=1;i<=1000010;i++)
		a[i]=a[i-1]+pre(i*3+7);
}
int main()
{
	int t;
	fun();
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		printf("%d\n",a[n]);
	}
}


你可能感兴趣的:(数学)