【问题标题】:How to fix runtime error on sieve, the runtime error is signed integer overflow: 46349*46349?如何修复筛子上的运行时错误,运行时错误是有符号整数溢出:46349*46349?
【发布时间】:2020-02-27 14:57:28
【问题描述】:

当我尝试使用 sieve 时,它​​给了我“运行时错误:有符号整数溢出:46349 * 46349 不能在类型 'int' 中表示”对于 long long int j = i*i; line.. 但是变量 j 已经是 long long int,而不是 int,为什么它仍然给我错误?

#include<bits/stdc++.h>
using namespace std;

bool Eliminated[1000001];
int N;

void Sieve(){
    Eliminated[1]=true;
    for(int i = 2;i<=1000000;i++){
        if(Eliminated[i]==false){
            long long int j = i*i;
            while(j<=1000000){
                Eliminated[j]=true;
                j=j+i;
            }
        }
    }
}

int main(){
    Sieve();
    cin>>N;
    long long int arr[N];
    for(int i = 0;i<N;i++){
        cin>>arr[i];
        long long int temp = sqrt(arr[i]);
        if(temp*temp==arr[i]){
            if(Eliminated[temp]==false){
                cout<<"YES"<<endl;
            }else{
                cout<<"NO"<<endl;
            }
        }else{
            cout<<"NO"<<endl;
        }
    }
}

【问题讨论】:

  • 这能回答你的问题吗? Long integer overflow in C++ 虽然这里有一个变量而不是字面量,但原理是一样的:表达式的类型不是由其上下文决定的,而是由表达式本身决定的:这里只是 i*i
  • 谢谢.. 它回答了我的问题

标签: runtime-error


【解决方案1】:

对于“long long”类型,有规定的最小长度要求 - long long int 必须至少与“long”一样长。循环内的每次迭代都没有满足这一点(2*2 = 4 不满足最低要求)。

请随时查看此页面了解更多详情。

What is the difference between "long", "long long", "long int", and "long long int" in C++?

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    相关资源
    最近更新 更多