hdu 4715 Difference Between Primes【筛法快速求素数表+思维】
2016-04-09 17:43
537 查看
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
2013 ACM/ICPC Asia Regional Online
—— Warmup
题目大意:
给你一个偶数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"); } }
相关文章推荐
- React:纯属性(pure prop),受控属性(controlled prop),半受控属性(half-controlled prop),一次性属性(onetime-prop)
- Java中的WeakReference讲解
- HTML常见标签学习和笔记总结
- Preference Learning——Introduction
- 安卓 json解析如何使用与讲解
- HTML中div垂直居中的三种方式
- a 标签中调用js的几种方法
- js confirm()方法的使用方法实例
- 用VS2013搭建前端开发环境的心得
- JSTL标签用法
- JavaScript里的类和继承
- CSS3实例教程:详解calc()函数功能
- 隐藏(删除) Preference 小结
- 优就业JS教程-JavaScript创建对象4种方法详解
- 16链表的反转|剑指offer
- [BZOJ 1012][JSOI2008]最大数maxnumber
- leetcode- Delete Node in a Linked List&Remove Linked List Elements
- <a href="javascript:void(0)" onclick="ff()" ></a> 用法解析
- 4行代码实现js模板引擎
- 关于node.js资料集