Open In App

How to Use int as long long int for Competitive Programming?

Improve
Improve
Like Article
Like
Save
Share
Report

Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required.

Case 1: Big integer input without redefining int as long long int
Case 2: Big integer input with redefining int as long long int

Case 1: Big integer input without redefining int as long long int

Example: 

C++




// C++ program to demonstrate Overflow in Implicit Conversion itself
 
// Importing input output libraries
#include <iostream>
 
using namespace std;
 
// Main driver method
int main()
{
    // 10 raised to the power of 10
    int x = 1e10;
 
    // Printing the number
    cout << x << endl;
 
    // As return type of main was integer type
    return 0;
}


Output: 

prog.cpp: In function ‘int main()’:
prog.cpp:5:10: warning: overflow in implicit constant conversion [-overflow]
 int x = 1e10; 
         ^

Output Explanation:

It is because the range of numbers integer data type can hold is 4 bytes meaning it can hold integer numbers ranging from -2,147,483,647 to 2,147,483,647. Here in our case, the output exceeds the maximum integer a variable can hold so do throw a warning of implicit constant conversion. So we do have to use a long datatype as it can hold 8 bytes. In order to rectify the same, we need to redefine int. However, the program will still throw an error as the datatype of the main also changes. So defining them to int so that our speed in contests can increase. (ie) #define int long long int.

Case 2: Big integer input with redefining int as long long int 

Example:

C++




// C++ program to demonstrate longlongint approach
 
// Including all basic libraries
#include <bits/stdc++.h>
using namespace std;
 
// Main driver method with int32_t return type
int32_t main()
{
    // Calculating size of Integer data type
    // using sizeof() method
    cout << "size of int = " << sizeof(int) << '\n';
 
// Defining int as long long int
#define int long long int
 
    // Calculating new size of Integer data type
    // again using standard sizeof() method
    cout << "new size of int = " << sizeof(int) << '\n';
 
    // Big custom input integer
    int x = 1e18;
 
    // Print and display this big integer value
    cout << "value of x = " << x << endl;
 
    return 0;
}


Output

size of int = 4
new size of int = 8
value of x = 1000000000000000000

Time Complexity: O(1)
Auxiliary Space : O(1)

Note: This is generally used in competitive programming problems as it will accept all input sizes.



Last Updated : 14 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads