寻找质数

     刚看到ACM的一道赛题,很简单:

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

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

Output:

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

T is about 100.

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

样例输入

1
8

样例输出

3 5

整体来说就是去寻找素数,所以,这个ACM赛题我觉得就是在考察寻找素数的算法。而这个算法简单的来说,就是挨个的进行尝试,但是很显然,这是很慢的。即使你只是循环到sqrt(number);

在网上看到了一种新的方式,对于我来说是一种新的方式,

就是说,对于一些比5大的素数,她们都是在6的倍数的上下分布的,比如5.7     11 13    17 19

不一而是。根据这个想法,很简单的就能写出一种新的算法:下面就是我这道题的C++代码实现

#include <iomanip>
#include <math.h>
#include <iostream>
using namespace std;
bool judge(int num){
    if(num ==2|| num==3 ){//这是对比较小的数进行排除
        return 1 ;
    }
    if(num %6!= 1&&num %6!= 5){ //然后进行判断是不是在6的两侧,在六的两测是素数的必要不充分条件
        return 0 ;
    }
    int index =sqrt( num);
    for(int i= 5;i <=index; i+=6 ){  //所以说在6的倍数两侧的也可能不是质数,这样就简单多了。循环的次数少多了
       return ((num %i== 0||num %(i+ 2)==0)==1?0:1);
    }                           
}
void FindAndOut(int number){
   if(judge(2)&&judge(number-2)){
        cout<<setiosflags(ios::left)<<setw(4)<<2<<(number-2)<<endl;
    }
   for(int i=3;i<(number/2);i+=2){
       if(judge(i)&&judge(number-i)){
        cout<<setiosflags(ios::left)<<setw(4)<<i<<(number-i)<<endl;
        break;
       }
   }
}
using namespace std;
int main(){
    int n;
    int *num;
    cin>>n;
    num = new int[n];
    for(int i=0;i<n;i++){
        cin>>num[i];
    }
    for(int i=0;i<n;i++){
        FindAndOut(num[i]);
    }
    delete []num;
    return 0;

}

猜你喜欢

转载自www.cnblogs.com/kaixiang-liu/p/9111471.html