hdu 4715 Difference Between Primes【筛法快速求素数表+思维】

针对一个数学猜想,即任意一个偶数都可以表示为两个素数之差,本文介绍了一个算法解决方案。该方案通过高效的素数判断方法,在限定的时间内找出满足条件的最小素数对,并处理了包括负数在内的各种边界情况。

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

Difference Between Primes

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3215    Accepted Submission(s): 913


Problem Description
All you know Goldbach conjecture.That is to say, Every even integer greater than 2 can be expressed as the sum of two primes. Today, skywind present a new conjecture: every even integer can be expressed as the difference of two primes. To validate this conjecture, you are asked to write a program.
 

Input
The first line of input is a number nidentified the count of test cases(n<10^5). There is a even number xat the next nlines. The absolute value of xis not greater than 10^6.
 

Output
For each number xtested, outputstwo primes aand bat one line separatedwith one space where a-b=x. If more than one group can meet it, output the minimum group. If no primes can satisfy it, output 'FAIL'.
 

 Sample Input
3
6
10
20
 


Sample Output
11 5
13 3
23 3

Source
 
 题目大意:
给你一个偶数n,让你求出两个素数,使得这两个素数相减等于n,输出要保证这两个素数是最小的组合。
思路:
首先我们确定一下总体的思路,我们既然是要找两个素数,最直接能够想到的就是两层for枚举i,j,使得i-j==n即输出,但是因为n比较大,所以导致两层for的i,j也是要比较大, 10^6*10^6是一定会超时的,这个思路基本上现在是可以pass了,这个时候我们可以想想如何改变式子来达到优化算法。
我们要找i-j==n,n是已知的,从两个未知找一个已知。我们不如让n,j位子互换变成:i-n==j,辣么我们就相当于一个未知一个已知找一个未知,但是这个未知其实我们相当于知道了,因为我们这个时候只需要判断一下j是否是素数即可。
辣么就会节省好多好多好多好多好多时间。
另外这样确定了之后直接敲然后直接交是会WA的。因为数据范围给的是:数据不会大于10^6,辣么-4也是属于可行范围啊。所以我们还需要判断一下负数的问题。把整个思路都敲定了之后,我们就可以一发AC辣~
AC代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;
int Is_or[1500000];
void init()
{
    memset(Is_or,0,sizeof(Is_or));
    Is_or[0]=1;
    Is_or[1]=1;
    int a,b;
    for(int j=2;j<sqrt(1500000);j++)
    {
        if(Is_or[j]==0)
        for(int k=j+j;k<=1500000;k+=j)
        {
            Is_or[k]=1;
        }
    }
}
int main()
{
    init();
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,flag=0;
        scanf("%d",&n);
        int ans1,ans2;
        if(n<0) {flag=1,n=-n;}
        int ok=0;
        for(int i=n;i<1500000;i++)
        {
            if(Is_or[i]==0)
            {
                if(Is_or[i-n]==0)
                {
                    ok=1;
                    ans1=i;
                    ans2=i-n;
                    break;
                }
            }
        }
        if(ok==1)
          if(!flag) printf("%d %d\n",ans1,ans2);
          else printf("%d %d\n",ans2,ans1);
        else printf("FAIL\n");
    }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值