Facile 0 risolte 0% di accettazione

Factorial

Multiply all positive integers up to n.

Cosa imparerai

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

Problema

Mostra traduzione

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!.

Vincoli

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

Esempi

Esempio 1
Input:
n = 5

Output atteso:
expected = 120
Input:
long long n = 5;

Output atteso:
long long expected = 120;
Input:
long n = 5;

Output atteso:
long expected = 120;

Spiegazione

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

Esempio 2
Input:
n = 0

Output atteso:
expected = 1
Input:
long long n = 0;

Output atteso:
long long expected = 1;
Input:
long n = 0;

Output atteso:
long expected = 1;

Spiegazione

0! is defined as 1.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.