首页 > 代码库 > SDUT Fermat’s Chirstmas Theorem(素数筛)

SDUT Fermat’s Chirstmas Theorem(素数筛)

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
果然蛋疼的一道题,题意说的很清楚,就用素数筛暴力就可以了,有一个坑就是比如范围是 1-2 这时1也是符合条件的,因为      1==4*0+1且1==0*0+1*1(虽然1不是素数,但为什么会有有这种数据?)
<pre name="code" class="html">#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <algorithm>
#include <set>
#include <vector>
#include <string>
#include <map>
#include <queue>
using namespace std;
const int maxn= 1000010;
int num=0;
int vis[maxn],prime[maxn];
void init_prime()
{
	memset(vis,1,sizeof(vis));
	vis[0]=0;vis[1]=0;
	for(int i=0;i<=maxn;i++)
	{
		if(vis[i])
		{
			prime[++num]=i;
		    for(int j=1;j*i<=maxn;j++)
			vis[j*i]=0;
		}
	}
}
int main()
{
	int L,U,i;
	init_prime();
	while(scanf("%d%d",&L,&U)!=EOF)
	{
		int cnt1=0,cnt2=0;
		if(L==-1&&U==-1) break;
		for(i=0;i<=num;i++)
		{
			if(prime[i]&&prime[i]>=L&&prime[i]<=U)
			{
				if((prime[i]-1)%4==0)
					cnt2++;
				cnt1++;
			}
		}
		if(L<=2&&U>=2)
			cnt2++;
		printf("%d %d %d %d\n",L,U,cnt1,cnt2);
	}
	return 0;
}
 



SDUT Fermat’s Chirstmas Theorem(素数筛)