设为首页 加入收藏

TOP

POJ中和质数相关的三个例题(POJ 2262、POJ 2739、POJ 3006)(二)
2019-06-11 10:08:10 】 浏览:267
Tags:POJ 中和 相关 三个 例题 2262 2739 3006
质数2,筛中只包含奇数;第2步之后,得到素数3,一直做下去,直到筛子为空时结束。

      采用这个思想,用如下循环完成对flag数组的设置。

       for(i=2;i<1000000;i++)      // 用筛法构建质数表

       {

        if (flag[i]=='1')

                     for (j=2*i;j<1000000;j+=i)

                            flag[j]='0';

    }

      (4)源程序2。

#include <iostream>

using namespace std;

int main()

{

    char flag[1000000];

       int i,j,n;

    for (i=2;i<1000000;i++)

              flag[i]='1';

       for(i=2;i<1000000;i++)      // 用筛法构建质数表

       {

        if (flag[i]=='1')

                     for (j=2*i;j<1000000;j+=i)

                            flag[j]='0';

    }

    while(cin>>n&&n)

       {

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

          {

          if(flag[i]=='1' && flag[n-i]=='1')

                {

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

             break;

                }

          }

       }

    return 0;

}

      将源程序1和2分别提交给POJ评判系统,可得到如图1所示的评判结果。从结果可以看出,源程序2的执行效率比源程序1高,当然所占用的存储空间也比源程序1要多。可以说是“用空间换时间”。  

图1  POJ给出的评判结果

 

【例2】Sum of Consecutive Prime Numbers (POJ 2739)

Description

Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.

Your mission is to write a program that reports the number of representa

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目