我正在尝试打印给定数量的素数的数量。我的代码对于某些输入可以正常工作,但是对于其他输入,它将被终止,我不明白为什么。
输入样例:
1
561473
输出:
2
输入样例:
1
10093
程序终止。
在某些时候,我认为这可能是浮点异常,但我不知道原因。我尝试调试每行代码,发现程序在此代码行终止:
while(ull(n%mem[j]) == 0) {
我仍然无法理解为什么此代码仅在某些特定输入时才中断。我也尝试过不使用类型转换,但仍然给我同样的问题。我尝试打印异常,但是该程序刚刚终止,没有显示任何错误。
#include <iostream>
#include <string>
#include <climits>
#include <stdexcept>
#include <algorithm>
#include <set>
#include <cmath>
using namespace std;
typedef unsigned long long ull;
ull RANGE = sqrt(10000), num;
unsigned int i;
set<ull> arr;
ull mem [10000000];
bool isPrime(unsigned long long n) {
if(n%2 == 0)
return false;
for( int i = 3; i <= sqrt(n); i+=2) {
if(n%i == 0)
return false;
}
return true;
}
void hungry() {
while(true) {
if(num > RANGE)
break;
if(isPrime(num)) {
mem[i++] = num;
}
num += 2;
}
}
int main() {
ios_base::sync_with_stdio (false);
cin.tie(NULL);
num = 3; i = 1; mem [0] = 2;
hungry();
ull ip, n, temp;
cin >> ip;
while(ip) {
cin >> n;
arr.clear();
temp = (ull) sqrt(n);
if(temp > RANGE) {
RANGE = temp;
hungry();
}
if(n == 1)
cout << 0 << "\n";
else {
while(n%2 == 0) {
arr.insert(2);
n = n/2;
}
for(int j = 1; mem[j] <= (ull)sqrt(n); j++){
while(ull(n%mem[j]) == 0) {
arr.insert(mem[j]);
n = (ull)n/mem[j];
}
}
if(n > 2)
arr.insert(n);
cout << arr.size() << "\n";
}
ip--;
}
return 0;
}
最佳答案
问题在于hungry
仅以素数填充mem
到n
的平方根。当while (mem[j] <= (ull)sqrt(n))
循环到达这些结尾时,mem[j]
是0
,而不是质数之一。然后,您尝试执行n % mem[j]
,该操作导致被0除。
将循环更改为:
while (mem[j] > 0 && mem[j] <= (ull)sqrt(n))
关于c++ - 进程终止,状态为-107374167,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303820/