设为首页 加入收藏

TOP

POJ中和质数相关的三个例题(POJ 2262、POJ 2739、POJ 3006)(一)
2019-06-11 10:08:10 】 浏览:264
Tags:POJ 中和 相关 三个 例题 2262 2739 3006

      质数(prime number)又称素数,有无限个。一个大于1的自然数,除了1和它本身外,不能被其他自然数整除,换句话说就是该数除了1和它本身以外不再有其他的因数;否则称为合数。
      最小的质数是2。

【例1】Goldbach's Conjecture (POJ 2262)

Description

In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in which he made the following conjecture:

Every even number greater than 4 can be

written as the sum of two odd prime numbers.

For example:

8 = 3 + 5. Both 3 and 5 are odd prime numbers.

20 = 3 + 17 = 7 + 13.

42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23.

Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but it is too long to write it on the margin of this page.)

Anyway, your task is now to verify Goldbach's conjecture for all even numbers less than a million.

Input

The input will contain one or more test cases.

Each test case consists of one even integer n with 6 <= n < 1000000.

Input will be terminated by a value of 0 for n.

Output

For each test case, print one line of the form n = a + b, where a and b are odd primes. Numbers and operators should be separated by exactly one blank like in the sample output below. If there is more than one pair of odd primes adding up to n, choose the pair where the difference b - a is maximized. If there is no such pair, print a line saying "Goldbach's conjecture is wrong."

Sample Input

8

20

42

0

Sample Output

8 = 3 + 5

20 = 3 + 17

42 = 5 + 37

      (1)编程思路1。

      对每个输入的n,从小到大依次对3~n/2之间的奇数i进行穷举,若i和n-i均是质数,则找到一组解,退出穷举。

判断一个数num是否为质数的方法是:用2~ 中的每一个整数m去除num,若某一个m能整除num,则num不是质数;否则,m是质数。

      (2)源程序1。

#include <iostream>

#include <cmath>

using namespace std;

bool isPrime(int num)

{

    int m;

    if(num==2) return true;

    for(m=2;m<=(int)sqrt((double)num);m++)

        if (num%m==0)

         return false;

    return true;

}

int main()

{

    int n,i;

    while(cin>>n&&n)

       {

       for(i=3;i<=n/2;i+=2)

          {

          if(isPrime(i) && isPrime(n-i))

                {

             cout<<n<<" = "<<i<<" + "<<n-i<<endl;

             break;

                }

          }

       }

    return 0;

}

      (3)编程思路2。

      上面的程序在穷举时,对每个穷举的整数i,都要调用函数isPrime(i) 和isPrime(n-i)来判断i和n-i是否为质数。实际上,可以预先生成一个判定数组flag[1000000],并且为了节省存储空间,可将flag数组定义为char类型(每个元素只占一个字节)。元素flag[i]==’1’表示整数i是质数;flag[i]==’0’表示整数i不是质数。

      初始化数组flag的所有元素都为’1’,然后采用Eratosthenes筛法进行处理。

       Eratosthenes筛法的基本思想是:把某范围内的自然数从小到大依次排列好。宣布1不是质数,把它去掉;然后从余下的数中取出最小的数,宣布它为质数,并去掉它的倍数。在第1步之后,得到

首页 上一页 1 2 3 4 5 6 下一页 尾页 1/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇最后一个非零数字(POJ 1604、POJ.. 下一篇POJ数据的输入输出格式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目