美文网首页
hdoj1397 素数筛选

hdoj1397 素数筛选

作者: 科学旅行者 | 来源:发表于2016-07-12 19:59 被阅读148次

题目描述:

Problem Description
Goldbach's Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2. This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if any, for a given even number. The problem here is to write a program that reports the number of all the pairs of prime numbers satisfying the condition in the conjecture for a given even number.A sequence of even numbers is given as input. Corresponding to each number, the program should output the number of pairs mentioned above. Notice that we are interested in the number of essentially different pairs and therefore you should not count (p1, p2) and (p2, p1) separately as two different pairs.
Input
An integer is given in each input line. You may assume that each integer is even, and is greater than or equal to 4 and less than 2^15. The end of the input is indicated by a number 0.
Output
Each output line should contain an integer number. No other characters should appear in the output.
Sample Input
6
10
12
0
Sample Output
1
2
1

题意:

输入一个数,使两个素数p1和p2之和等于这个数。p1 + p2 = n 和p2 + p1 = n算一对组合,问一共有多少对组合。

此题肯定要用素数筛选,而在求组合的对数时,直接求多半会超时(n最大可取2的15次方)。而通过此题可以看出,实际上我们只需取一半来循环就可以了,因为其中有重复(比如:5 + 7 = 12 和 7 + 5 = 12)。
为了减少运行时间,此题可以先打表。

参考代码:

#include <iostream>
#include <vector>
using namespace std;
int primes[32770];
int prime(int num) {
    int flag = 1;
    if (num == 1) {
        return 0;
    }
    for (int k = 2;k * k <= num;++k) {
        if (num % k == 0) {
            flag = 0;
            break;
        }
    }
    return flag;
}
void lastest_prime() {
    for (int num = 2;num <= 32768;++num) {
        int flag = prime(num);
        if (flag) {
            primes[num] = 1;
        }
        else {
            primes[num] = 0;
        }
    }
}
int main() {
    int p;
    int res;
    lastest_prime();
    while (cin >> p && p) {
        int i;
        res = 0;
        for (i = 0;i <= p / 2;++i) {
            if (primes[i] && primes[p-i]) {
                res++;
            }
        }
        cout << res << endl;
    }
    return 0;
}

相关文章

  • hdoj1397 素数筛选

    题目描述: Problem DescriptionGoldbach's Conjecture: For any e...

  • Algorithm

    素数筛选

  • 素数筛选

    今天在面试时被问到了一个问题:求不大于n的最大素数,当时只想出暴力解法,回来查资料找到了正确的求解方法。 素数筛法...

  • 筛选素数/筛选质数

  • 区间素数线性筛选

    区间素数线性筛选 假设应用场景为求一个区间长度远小于右端点的所有素数,该区间为 。如若使用朴素素数线性筛选,则需...

  • 素数线性筛选

    素数线性筛选 素数的定义是除了1和自身能被整除外,没有其他数能被它整除。除此之外,1既不是素数,也不是合数。因此,...

  • 素数算法

    寻找素数的算法有很多,最著名应是筛选法,以下是笔者用JavaScript编写的一个找素数的函数,借鉴了各种找素数的...

  • 筛选法求素数

  • RSA加密解密算法—数论基础

    本章涉及知识点1、素数的定义2、寻找素数算法—短除法3、寻找素数算法—筛选法4、互质关系5、欧拉函数的证明6、欧拉...

  • 筛选N以内的素数

    1.题目描述用简单素数筛选法求N以内的素数。 2.格式与样例:输入格式N输出格式2~N的素数输入样例100输出样例...

网友评论

      本文标题:hdoj1397 素数筛选

      本文链接:https://www.haomeiwen.com/subject/iglsjttx.html