Fermat’s Chirstmas Theorem
Time Limit: 1000MS Memory limit: 65536K
题目描述
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.
To illustrate, each of the following primes can be expressed as the sum of two squares:
5 = 22 + 12
13 = 32 + 22
17 = 42 + 12
41 = 52 + 42
Whereas the primes 11, 19, 23, and 31 cannot be expressed as a sum of two squares. Write a program to count the number of primes that can be expressed as sum of squares within a given interval.
输入
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.
输出
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.
示例输入
10 20 11 19 100 1000 -1 -1
示例输出
10 20 4 2 11 19 4 2 100 1000 143 69
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int M=1000005;
int prime[1000005];
int flag[1000005];
int p_num;
void getP()
{
int i, j;
p_num = 0;
memset(flag, 0, sizeof(flag) );
for ( i = 2; i < M; i++ )
{
if ( !flag[i] ) prime[p_num++] = i;
for ( j = 0; j < p_num && i * prime[j] < M; j++ )
{
flag[ i * prime[j] ] = 1;
}
}
}
int main()
{
int l,u,x,y;
getP();
while(scanf("%d%d",&l,&u))
{
x=0;
y=0;
if(l==-1&&u==-1)
break;
for(int i=0;i<p_num;i++)
{
if(prime[i]>=l&&prime[i]<=u)
{
x++;
if(prime[i]%4==1)
y++;
}
if(prime[i]>u)
break;
}
if(l<=2&&u>=2) y++;
printf("%d %d %d %d\n",l,u,x,y);
}
return 0;
}
本文介绍了一道关于费马圣诞定理的程序设计题,该定理阐述了奇质数能表示为两个平方数之和的条件。文章包含问题描述、输入输出示例及解答代码,通过算法验证指定区间内满足条件的质数数量。

946

被折叠的 条评论
为什么被折叠?



