Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Sum of the First N Numbers

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Print 1 + 2 + 3 + … + n.

Input

A single integer n.

Output

The sum.

Constraints

A loop of 10^9 steps is too slow. Use the formula n × (n + 1) / 2 — and a 64-bit integer, because the result can reach 5 × 10^17.

Example 1

Input

5

Output

15

Example 2

Input

1

Output

1

Hints

  1. Pair 1 with n, 2 with n − 1, …: every pair sums to n + 1.
  2. There are n / 2 such pairs.

Approach

The sum is n(n + 1) / 2 (Gauss). One of n and n + 1 is even, so the division is exact. With n = 10^9 the product is about 10^18, which needs a 64-bit integer — multiply in 64 bits before dividing.

Complexity: O(1) time · O(1) space

Solution

C++ solution

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

int main() {
    long long n;
    cin >> n;
    cout << n * (n + 1) / 2 << "\n";
    return 0;
}

Python solution

n = int(input())
print(n * (n + 1) // 2)

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(n * (n + 1) / 2);
    }
}

Solve Sum of the First N Numbers online · All practice problems