Facile 0 résolus 0 % de réussite

Factorial

Multiply all positive integers up to n.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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

Contraintes

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

Exemples

Exemple 1
Entrée :
n = 5

Sortie attendue :
expected = 120
Entrée :
long long n = 5;

Sortie attendue :
long long expected = 120;
Entrée :
long n = 5;

Sortie attendue :
long expected = 120;

Explication

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

Exemple 2
Entrée :
n = 0

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

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

Sortie attendue :
long expected = 1;

Explication

0! is defined as 1.

Comment l'aborder

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

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

O(n) 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.