Tous les défis
Facile 0 résolus 0 % de réussite

Triangular Number

Add the integers from 1 through n.

Ce que vous allez apprendre

  • 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

Problème

Afficher la traduction

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.

Contraintes

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

Exemples

Exemple 1
Entrée :
n = 10

Sortie attendue :
expected = 55
Entrée :
long long n = 10;

Sortie attendue :
long long expected = 55;
Entrée :
long n = 10;

Sortie attendue :
long expected = 55;

Explication

1 + 2 + … + 10 = 55.

Exemple 2
Entrée :
n = 0

Sortie attendue :
expected = 0
Entrée :
long long n = 0;

Sortie attendue :
long long expected = 0;
Entrée :
long n = 0;

Sortie attendue :
long expected = 0;

Explication

No numbers to add, so the sum is 0.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.