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

Factorial

Multiply all positive integers up to n.

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

  • Multiply a sequence of numbers with a loop
  • Start a product at 1 instead of 0
  • See how quickly factorials grow

問題

翻訳を表示

The factorial of n, written n!, is 1 × 2 × … × n. By definition 0! = 1.

Implement factorial(n).

Input

n: A non-negative integer.

Output

Return n!.

制約

0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.

例

例 1
入力:
n = 5

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

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

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

解説

1 × 2 × 3 × 4 × 5 = 120.

例 2
入力:
n = 0

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

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

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

解説

0! is defined as 1.

解き方のヒント

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

ヒント 1

Factorial multiplies all integers from 1 up to the given number.

ヒント 2

An iterative running product is enough, and 0 has a special defined result.

ヒント 3

Because the input is small, overflow is the main detail to watch for in other languages.

目安の計算量

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

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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