Einfach 0 gelöst 0% Erfolgsquote

Triangular Number

Add the integers from 1 through n.

Das lernst du

  • 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

Übersetzung anzeigen

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.

Einschränkungen

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

Beispiele

Beispiel 1
Eingabe:
n = 10

Erwartete Ausgabe:
expected = 55
Eingabe:
long long n = 10;

Erwartete Ausgabe:
long long expected = 55;
Eingabe:
long n = 10;

Erwartete Ausgabe:
long expected = 55;

Erläuterung

1 + 2 + … + 10 = 55.

Beispiel 2
Eingabe:
n = 0

Erwartete Ausgabe:
expected = 0
Eingabe:
long long n = 0;

Erwartete Ausgabe:
long long expected = 0;
Eingabe:
long n = 0;

Erwartete Ausgabe:
long expected = 0;

Erläuterung

No numbers to add, so the sum is 0.

So gehst du vor

Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.

Hinweis 1

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

Hinweis 2

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

Hinweis 3

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

Erwartete Komplexität

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

Die beste bestandene Lösung jedes Coders. Schnellere, sparsamere und besser bewertete Lösungen stehen weiter oben.

Noch keine bestandene Lösung. Löse sie und hol dir Platz eins.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.