为什么编写的代码在执行时出现溢出错误
why is the code written is having overflow error when executed
该程序是找到数字的最大质因数 600851475143.It 对于任何小于max_int的给定否完美工作。
我在代码块中运行代码。
#include<iostream>
using namespace std;
int main()
{
unsigned long long a =600851475143 ,prime=2,i,j;
for(i = 1;i < a/2;i++) {
int count =1;
if( (a%i)==0) {
for( j = 2;j <=(i/2);j++)
if(i%j==0)
count = 0;
if(count == 1)
prime = i;
}
}
cout<<prime;
}
预期结果是600851475143的最大质因数但是输出什么都没有,只是空白屏幕
我认为你会得到一个时间溢出,你正在做最少的 600851475143/2 次操作,考虑到 1 mil. 的操作大约在 ~ 0.1s 内执行,这实际上是很多;你可以通过不去 a/2 而是去 sqrt(a) 来优化它,更多关于为什么在这里 (https://en.wikipedia.org/wiki/Primality_test)
#include<iostream>
using namespace std;
int main(){
unsigned long long a = 600851475143 ,prime = 2,i,j;
for(i = 1; i*i < a; i++){
int count = 1;
if((a%i) == 0){
//check if i is prime
for(j = 2; j*j <= i && count;j++)
if(i%j == 0)
count = 0;
if(count == 1){
prime = max(prime,i);
}
//check if a/i is prime
count = 1;
for(j = 2; j*j <= a/i && count;j++)
if(a/i%j == 0)
count = 0;
if(count == 1){
prime = max(prime, a/i);
}
}
}
cout << prime;
}
现在,我们将有大约 1 mil. 由 First For 执行的操作。
此外,检查 a/i 是否也是素数也会很棒,因为一个数字可以
相关文章:
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 使用 strcat 获取缓冲区溢出错误
- 如何修复此特征矩阵反演溢出错误?
- 如何修复递归函数导致的堆栈溢出错误?C++
- 没有 climits 库的溢出错误
- 当我尝试为结构分配新指针时出现堆栈溢出错误
- 应该如何读取堆缓冲区溢出错误消息?
- 初始化数组并出现堆栈溢出错误
- 将 Vector<int> 推送到 Vector<vector 时出现堆溢出错误<int>>
- 为什么 #include <string> 在这里防止堆栈溢出错误?
- 我在 36603 以上输入的任何数组大小时都会返回"堆栈溢出"错误。如何使字符串能够捕获整个.txt文件?
- Boost::序列化存储结构时的堆栈溢出错误
- GetModuleFilenameEx返回0,getlasterror返回溢出错误.我究竟做错了什么
- std::堆栈和堆栈溢出错误的数组分配
- 为什么编写的代码在执行时出现溢出错误
- C 堆栈溢出错误
- 编译器或 CPU 中的 64 位溢出错误
- 创建DLL导出对象时发生堆栈溢出错误