Practice › Basics
Sum of Two Numbers
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Read two integers a and b and print their sum.
Input
One line with two integers a b.
Output
Print a + b.
Constraints
- -10^12 ≤ a, b ≤ 10^12
Tip: these values don't fit in a 32-bit
int— uselong long(C++) orlong(Java).
Example 1
Input
3 5
Output
8
Example 2
Input
-7 2
Output
-5
Hints
- Read both numbers and print a + b — the only trap is the size of the values.
- Values go up to 10^12, so a 32-bit int overflows. Use long long (C++) or long (Java).
Approach
Read a and b into 64-bit integers and print their sum. A 32-bit int only holds about ±2.1 × 10^9, so 10^12 + 10^12 would overflow. Python integers never overflow.
Complexity: O(1) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long a, b;
cin >> a >> b;
cout << a + b << "\n";
return 0;
}Python solution
a, b = map(int, input().split())
print(a + b)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong(), b = sc.nextLong();
System.out.println(a + b);
}
}