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
计算两个数之间的素数的个数以及满足条件p = a ^ 2 + b ^2和条件p = 4*c+1的素数的个数(其实这两个条件等价)。
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <algorithm> #define MAX 1000000 using namespace std; int su[MAX+10] = {2,3,5};//定义基本素数 int init() { int i,j,k,m = 2,bj; k = 3; for(i = 7;i <= 1000000;i = i + m)//6m,6m+1,6m+2,6m+3,6m+4,6m+5只需计算6m+1和6m+5是不是素数即可, //其它的,都能够被某个数整除,所以无需判断,肯定不是素数。接下来是6m+6,6m+7,6m+8,6m+9,6m+10,6m+11,如此,规律就显现出来了。 { bj = 1; m = 6 - m; for(j = 0;su[j]*su[j] <= i;j++)//su[j]里存放的是素数,su[j]*su[j]<=i相当于su[j] <= sqrt(i),这样可以节约时间 { if(i%su[j] == 0)//如果i能被某个素数整除,则i肯定不是素数 { bj = 0; break; } } if(bj == 1) su[k++] = i;//如果都不能整除,将i这个素数加入数组 } return k; } int main() { int k; k = init(); int L,U,x,y,num,sum; while(scanf("%d%d",&L,&U)!=EOF) { num = 0; sum = 0; int bj = 0; if(L == -1 && U == -1) break; for(x = 0;x < k;x++) { if(su[x] > U) break; if(su[x] >= L && su[x] <= U) { num++; if((su[x]-1)%4 == 0 || su[x] == 2)//满足p = 4*c+1的条件,另外,2也满足条件,因为可以1*1+1*1 = 2; { sum++; } } } printf("%d %d %d %d\n",L,U,num,sum); } return 0; }