c++long-integercout

To print big integers using expressions why we need to declare initial variable as long too


so basically I had a code where I wanted to get the cube of the given integer the input can be as big as 10^6 so when i used long long int and size_t and they did not work until I changed the data type of input to long long on a whim. Can someone please explain why this happened?

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

int main(){
    long long t;cin>>t;
    long long ans=t*t*t;
    cout<<ans;
    return 0;
}

also this happened even on while simply using cout instead of storing it in a variable first.


Solution

  • Why int t Causes an Overflow Error

    Consider the following program, where t is declared as a 4 byte integer:

    #include <iostream>
    using namespace std;
    int main(){
        int t;
        cin>>t;
        long long ans= t*t*t;
        cout<<ans;
        return 0;
    }
    

    When I input 1,000,000 as you have stated I receive an incorrect value:

    1000000
    -1486618624
    

    Since t is an 4 byte integer, The multiplication t*t*t will return a 4 byte integer, and then implicitly casted to an 8 byte integer when it is moved in ans

    However since a 4 byte integer can only store a value up to 2,147,483,647 and (10^6)^3 > 2,147,483,647. This results in an overflow error in the multiplication, yielding this erroneous negative value which is then casted to an 8 byte integer, when it is moved into ans (where it remains this erroneous value).

    Why long long t doesnt cause an Overflow Error

    Changing the declaration of t so that it is a long long:

    long long t;
    

    long long is an 8-byte integer, hence that the multiplication t*t*t will return an 8 byte integer and then moved in ans.

    An 8 byte integer can store values up to 18,446,744,073,709,551,615 and (10^6)^3 < 18,446,744,073,709,551,615 so they wont be an overflow and it will correctly output '1,000,000,000,000,000,000`.

    Explicit Casting to prevent overflow error

    Alternatively, you could leave t as an int and explicitly cast the multiplication t*t*t to a long long as follows:

        int t; cin>>t;
        long long ans= (long long) t*t*t;
    

    I believe this explicitly tells the compiler to store the result of the multiplication t*t*t as a 8 byte integer and not a 4 byte integer (which prevents the overflow)