【2018ICPC宁夏预选赛】Goldbach JAVA质数简单题


Description:

Goldbach's conjecture is one of the oldest and best-known unsolved problems in number theory and all of mathematics. It states:

Every even integer greater than 2 can be expressed as the sum of two primes.

The actual verification of the Goldbach conjecture shows that even numbers below at least 1e14 can be expressed as a sum of two prime numbers. 

Many times, there are more than one way to represent even numbers as two prime numbers. 

For example, 18=5+13=7+11, 64=3+61=5+59=11+53=17+47=23+41, etc.

Now this problem is asking you to divide a postive even integer n (2<n<2^63) into two prime numbers.

Although a certain scope of the problem has not been strictly proved the correctness of Goldbach's conjecture, we still hope that you can solve it. 

If you find that an even number of Goldbach conjectures are not true, then this question will be wrong, but we would like to congratulate you on solving this math problem that has plagued humanity for hundreds of years.

Input:

The first line of input is a T means the number of the cases.

Next T lines, each line is a postive even integer n (2<n<2^63).

Output:

The output is also T lines, each line is two number we asked for.

T is about 100.

本题答案不唯一,符合要求的答案均正确

样例输入
1
8
样例输出
3 5



思路:

题目给定一个数n,要求求两个质数的和等于这个数,输出两个质数。因为这个数很大,所以不能用暴力的做法。我通过观察前遛六万的质数表发现,每个质数之间的间隔大小不会随着数字的增大而增大,换句话说,就可以直接用n/2然后上下寻找两个质数直接输出就好。接下来遇到的一个问题就是如何求一个很大的数是否是质数,用以往sqrt(n)暴力的方法肯定是不行的,幸运的是发现了java内置了一个O(logn)的方法BigInteger.valueof(x).isProbablePrime(y); 直接就能很快的求出这个数的结果。

优化:通过质数表发现在两位数及其以上,末位数为1 3 7 9才有可能为质数,可以用这个规律来进行剪枝,需要消耗的时间会更少。


JAVA那个求质数的方法晚些还得再研究一下。一些概率的东西不是很明白。


AC代码

    public static void main(String[] args){
        int count = input.nextInt();
        for(int i=0;i<=count-1;i++){
            String str = input.next();
            long b = Long.valueOf(str);
            b /= 2;
            while(true){
                int get = (int)(b%10);
                if(get==1||get==3||get==5||get==7||get==9){
                    if(BigInteger.valueOf(b).isProbablePrime(2)&&BigInteger.valueOf(Long.valueOf(str)-b).isProbablePrime(2)){
                        break;
                    }else{
                        b+=2;
                    }
                }else{
                    b++;
                }
            }
            out.println(b+" "+(Long.valueOf(str)-b));
        }
        out.flush();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值