Fermat’s Chirstmas Theorem

本文介绍了费马圣诞节定理,即一个奇质数可以表示为两个平方数之和当且仅当它可以表示为4的倍数加1。通过提供示例和代码实现,详细解释了如何计算给定区间内能被表示为平方和的素数数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接

 

 

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

 

 

 

借用了一套高效素数打表的方法。

 

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
bool visit[1010000];
int prime[1000100];
int num = 0;
void init_prim(int n)
{
    memset(visit, true, sizeof(visit));
    for (int i = 2; i <= n; ++i)
    {
        if (visit[i] == true)
        {
            num++;
            prime[num] = i;
        }
        for (int j = 1; ((j <= num) && (i * prime[j] <= n));  ++j)
        {
            visit[i * prime[j]] = false;
            if (i % prime[j] == 0) break;
        }
    }
}
int main()
{
    init_prim(1000000);
    visit[0]=0;
    visit[1]=0;
    int l,p;
    int ans1,ans2;
    int x,y;
    while(scanf("%d%d",&l,&p))
    {
        if(l==-1&&p==-1)
            break;
        ans1=ans2=0;
        for(int i=0; i<=num; i++)
            if(prime[i]&&prime[i]>=l&&prime[i]<=p)
            {
                if((prime[i]-1)%4==0)
                    ans2++;
                ans1++;
            }
        if(l<=2&&p>=2)
            ans2++;
        printf("%d %d %d %d\n",l,p,ans1,ans2);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值