← All problems
Sum from 1 to N
Easy
4 solved
Sum from 1 to N
Given a positive integer N, print the sum of all integers from 1 to N.
For example, when N is 5 the answer is 1 + 2 + 3 + 4 + 5, which is 15.
A loop works fine here, but N can be as large as one million — so the answer will not fit in a small integer type in C, C++ or Java. Use a 64-bit type such as long long or long.
Input
A single line containing one integer N.
Output
A single integer: the sum 1 + 2 + ... + N.
Constraints
1 <= N <= 10^6
Example 1
Input
5
Output
15
1 + 2 + 3 + 4 + 5 = 15
Submit runs your code against 5 test cases — the 1 shown above plus 4 hidden ones covering the awkward cases. Run sample just tries the first example, which is usually what you want while you are still working it out.