Fermat’s Chirstmas TheoremCrawling in process...Crawling failedTime Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Description
In a letter dated December 25, 1640; the great mathematician Pierre de Fermat wrote to Marin Mersenne that he just proved that an odd prime p is expressible as p = a2 + b2 if and only if p is expressible as p = 4c + 1. As usual, Fermat didn’t include the proof, and as far as we know, never
wrote it down. It wasn’t until 100 years later that no one other than Euler proved this theorem.
Input
Your program will be tested on one or more test cases. Each test case is specified on a separate input line that specifies two integers L, U where L ≤ U < 1, 000, 000
The last line of the input file includes a dummy test case with both L = U = −1.
Output
L U x y
where L and U are as specified in the input. x is the total number of primes within the interval [L, U ] (inclusive,) and y is the total number of primes (also within [L, U ]) that can be expressed as a sum of squares.
Sample Input
10 20 11 19 100 1000 -1 -1
Sample Output
10 20 4 2 11 19 4 2 100 1000 143 69
Hint
题意:输入n,m。在此范围内输出素数的个数,以为可以拆分为平方和的素数的个数;
思路:因为范围过大,用普通的冒泡排序找素数肯定超时,所以我们要寻求效率更高的素数筛;提取出2,3,5三个素数,剩下的6,7,8,9,10,11可以用6n+1,6n+2,6n+3,6n+4,6n+5(当n=1)表示,但其中只有6n+1,和6n+5为素数,所以在n>1的情况也是如此、
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int prime[1000000]={2,3,5};
int k=3;
void is_prime()
{
int i,j;
int flag=0;
int gad=2;
for(i=7;i<=1000000;i+=gad)
{
flag=0;
gad=6-gad;
for(j=0;prime[j]*prime[j]<=i;j++)
{
if(i%prime[j]==0)
{
flag=1;
break;
}
}
if(flag==0)
{
prime[k++]=i;
}
}
}
int main()
{
int n,m,i;
int sum1,sum2;
is_prime();
while(~scanf("%d %d",&n,&m))
{
if(n==-1&&m==-1)
break;
sum1=0;
sum2=0;
for(i=0;i<k;i++)
{
if(prime[i]>m)
break;
if(prime[i]>=n&&prime[i]<=m)
{
{
sum1++;
}
if(prime[i]==2||(prime[i]-1)%4==0)
{
sum2++;
}
}
}
printf("%d %d %d %d\n",n,m,sum1,sum2);
}
return 0;
}