Read the question, write C++ on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read n and print 1 + 2 + … + n. If n is 0, print 0.
Use a long long — for large n the sum overflows a 32-bit int.
Input. One line: an integer n ≥ 0.
Output. One integer: the total.
Constraints
- 0 ≤ n ≤ 1000000
Examples
Input
5
Output
15
Input
1
Output
1
Hint
- A while loop can accumulate a running total.
- The formula n * (n + 1) / 2 needs no loop — but keep it in long long.
Show correct code
Peek only after you have tried. You can still Check your own version.
#include <iostream>
int main() {
long long n;
std::cin >> n;
std::cout << n * (n + 1) / 2 << "\n";
return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.