SDUT Fermat’s Chirstmas Theorem(素数筛)

费马于1640年圣诞节向Mersenne提出了一条关于素数表达为两个平方数之和的定理,并声称已找到证明,但未留下详细过程。直到一个世纪后,该定理才由欧拉给出证明。此题要求编写程序,在给定区间内找出所有能表示为两个平方数之和的素数。

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 = 2 2 + 1 2
13 = 3 2 + 2 2
17 = 4 2 + 1 2
41 = 5 2 + 4 2
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;
}
 



 
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值