哥德巴赫猜想认为“每一个大于2的偶数,都能表示成两个质数之和”。
给定一个大于2的偶数N,你能找到两个质数P和Q满足P<=Q并且P+Q=N吗?
Input
一个偶数N(4 <= N <= 1000000)
Output
输出P和Q。如果有多组解,输出P最小的一组。
Sample Input
10
Sample Output
3 7
import java.util.*; public class Main { static Scanner in = new Scanner(System.in); static int N=1000005; static boolean[] b=new boolean[N]; static void init(){ for (int i = 0; i < b.length; i++) { if(i%2==0) b[i]=false; else b[i]=true; } b[2]=true;b[1]=false; for (int i = 2; i <=Math.sqrt(N); i++) { if(b[i]){ for (int j = i+i; j < N; j+=i) { b[j]=false; } } } } public static void main(String[] args) { init(); while(in.hasNext()){ int n=in.nextInt(); List<Num> st=new ArrayList<Num>(); int p=0,q=0; while(p<=n){ if(b[p]&&b[n-p]&&p<=n-p){ Num c=new Num(p, n-p); st.add(c); } p++; } System.out.println(st.get(0).p+" "+st.get(0).q); } } } class Num{ int p; int q; Num(int p,int q){ this.p=p; this.q=q; } }
由于数据较多,所以我先打了一个素数表!