All challenges
Easy 0 solved 0% acceptance

Triangular Number

Add the integers from 1 through n.

What you'll learn

  • Add the numbers from 1 to n with a loop
  • Learn the formula n × (n + 1) / 2
  • Compare a loop with a constant-time formula

Problem

The n-th triangular number is 1 + 2 + … + n. A formula avoids looping over huge inputs. The 0th triangular number is 0.

Implement triangular_number(n).

Input

n: A non-negative integer.

Output

Return 1 + 2 + … + n.

Constraints

0 ≤ n ≤ 1,000,000,000. The result fits a signed 64-bit integer.

Examples

Example 1
Input:
n = 10

Expected output:
expected = 55
Input:
long long n = 10;

Expected output:
long long expected = 55;
Input:
long n = 10;

Expected output:
long expected = 55;

Explanation

1 + 2 + … + 10 = 55.

Example 2
Input:
n = 0

Expected output:
expected = 0
Input:
long long n = 0;

Expected output:
long long expected = 0;
Input:
long n = 0;

Expected output:
long expected = 0;

Explanation

No numbers to add, so the sum is 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Look for a pattern in the running totals instead of adding every number one by one.

Hint 2

Use the arithmetic-series shortcut based on the first and last terms, which avoids looping.

Hint 3

Be careful with the 0 case, and ensure your arithmetic stays within 64-bit limits.

Expected complexity

O(1) time, O(1) extra space

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.