【发布时间】: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