簡単 0件解決済み 正答率0%

Triangular Number

Add the integers from 1 through n.

このチャレンジで学べること

  • 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

問題

翻訳を表示

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.

制約

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

例

例 1
入力:
n = 10

期待される出力:
expected = 55
入力:
long long n = 10;

期待される出力:
long long expected = 55;
入力:
long n = 10;

期待される出力:
long expected = 55;

解説

1 + 2 + … + 10 = 55.

例 2
入力:
n = 0

期待される出力:
expected = 0
入力:
long long n = 0;

期待される出力:
long long expected = 0;
入力:
long n = 0;

期待される出力:
long expected = 0;

解説

No numbers to add, so the sum is 0.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。