为什么编写的代码在执行时出现溢出错误

why is the code written is having overflow error when executed

本文关键字:溢出 错误 执行 代码 为什么      更新时间:2023-10-16

该程序是找到数字的最大质因数 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 是否也是素数也会很棒,因为一个数字可以