【问题标题】:Any way to generate elements faster and check if they are prime?有什么方法可以更快地生成元素并检查它们是否是素数?
【发布时间】:2017-10-30 22:28:50
【问题描述】:

我有一个任务,这是要求

Write a program that finds the number of the prime numbers in a randomly 
generated row.

No more than 100 examples are set to the standard input. Each 
example is defined by two positive integers s and N per row (s <10^3, N <10^9). 
s sets a numerical row (by srand (s)) of length N, which is generated with 
rand ()% 1000.

Print out the count of all prime numbers.

我目前将此作为我的代码,在我的 PC 上,最大值需要 3 秒才能找到数字行中所有素数的计数。

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <stdio.h>

using namespace std;

bool isPrime(int num) {
   if (num <= 3) {
     return num > 1;
 } else if (num % 2 == 0 || num % 3 == 0) {
    return false;
 } else {
     for (int i = 5; i * i <= num; i += 6) {
         if (num % i == 0 || num % (i + 2) == 0) {
             return false;
         }
     }
     return true;
 }
}

int main()
{
int seed;

long long lenght;

while(cin >> seed >> lenght){

    srand(seed);

    unsigned long long totalPrimes = 0;

    for (int i = 0; i < lenght; ++i) {

        int prime = rand() % 1000;

        if (isPrime(prime)) {
            totalPrimes++;
        }
    }

    cout << totalPrimes << endl;

    int seed = 0;

    int lenght = 0;

 }


 return 0;
}

问题是这似乎没有他想要的足够快。有更快的方法吗?我尝试了多种方法,但都比我上面的代码慢。

【问题讨论】:

  • isPrime 中一遍又一遍地计算相同的素数是浪费时间。查找埃拉托色尼筛。使用筛子计算所有小于 1000 的素数并将结果存储在 std::set 中。记录std::set.中的所有输入数字
  • 审查工作代码可能最好发布在:codereview.stackexchange.com

标签: c++ variable-assignment


【解决方案1】:

您可以对算法进行改进

“所有编程都是缓存练习。” -Terje Mathisen

那么为什么要多次计算素数,只需存储它们并查看生成的随机数是否是其中之一,通过线性搜索或二分搜索。

如果您遍历所有数字一次以找到素数并将其存储在索引数组中,这样您就可以在 O(1) 而不是 O(log N) 中进行查找

if (primeList[x])
  totalPrimes++;

【讨论】:

  • 我认为遍历 0 到 1000 之间的所有 168 个素数对于每个数字来说并不是一个好主意。这样,您必须检查的内容比我的函数 isPrime() 更多,它最多只需要 4 个步骤。也许你有一个例子?我试过二分查找,速度比较慢。
  • @BorislavKirilov 我想你会惊讶于它与你其他需要做的所有'%'相比有多快。我会更新我的答案,因为我记得一个更快的方法。
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 2011-08-14
  • 2011-04-01
  • 2021-11-03
  • 2021-02-23
  • 2011-06-19
  • 1970-01-01
相关资源
最近更新 更多