Why is “int” not working correctly with “j” but long long is working fine?

情到浓时终转凉″ 提交于 2020-05-30 11:29:57

问题


This is my code with int j:

void solve(){
    unsigned long long n;
    cin>>n;
    unsigned long long sum = 0;
    int j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }
Input:
499993

Output:
6229295798864

but it is giving wrong output, and here is my code with long long j which is working fine:

void solve(){
    int n;
    cin>>n;
    unsigned long long sum = 0;
    long long j = 1;
    for(int i=3;i<n+1;i+=2){
        sum += ((4*i)-4)*(j);
        j++;
    }
    cout<<sum<<"\n";
    }
Input:
499993

Output:
41664916690999888

In this case value of j is well below 499993, which is in int range but still, it's not working. Why is it actually happening?

Here is the link to the actual problem. In case, you want to have a look.


回答1:


Notice that the result of ((4*i)-4)*(j) is an int, since both i and j are int types. The right hand side is promoted to unsigned long long only when adding ((4*i)-4)*(j) to sum. But the expression ((4*i)-4)*(j) already overflows the size of the int type for a large enough n before being promoted.

However, if you change either of i or j to unsigned long long, the expression ((4*i)-4)*(j) is evaluated to unsigned long long, safely inside the size limits.




回答2:


In the first code snippet in the expression

((4*i)-4)*(j)

of the assignment statement

sum += ((4*i)-4)*(j);

the both operands (4*i)-4) and (j) have the type int. So the type of the expression (the common type of the operands) is also int. But an object of the type int is not large enough to store the result value. So here an overflow takes place.

When the j is declared as having the type long long

long long j = 1;

then the common type of the expression above is also long long. It means that due to the usual arithmetic conversion this operand (4*i)-4) is also converted to the type long long. And an object of this type can store the result value provided for the inputted data.

You can check what are the maximum values that can be stored in objects of the type int and long long.

Here you are.

#include <iostream>
#include <limits>

int main() 
{
    std::cout << "The maximum value of an object of the type int is "
              << std::numeric_limits<int>::max()
              << '\n';

    std::cout << "The maximum value of an object of the type long long is "
              << std::numeric_limits<long long>::max()
              << '\n';

    return 0;
}

The program output might look like

The maximum value of an object of the type int is 2147483647
The maximum value of an object of the type long long is 9223372036854775807


来源:https://stackoverflow.com/questions/61817328/why-is-int-not-working-correctly-with-j-but-long-long-is-working-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!