Calculate a factorial
Calculate n! for an integer from 0 through 20. For example, 5! equals 5 × 4 × 3 × 2 × 1.
Course progress
Problem 3 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
n = 5
Expected output
120
What is happening?
Multiply every positive integer from 1 through 5: 1 x 2 x 3 x 4 x 5 = 120.
Solution strategy
Build the right mental model
Start the product at 1 and multiply by every integer from 2 through n. Restrict the input to 0 through 20 because 21! exceeds the range of long.
Core concepts
loops · validation
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for factorial
using System;
class Program
{
static long Factorial(int number)
{
if (number < 0 || number > 20)
throw new ArgumentOutOfRangeException("number");
long result = 1;
for (int factor = 2; factor <= number; factor++) result *= factor;
return result;
}
static void Main()
{
Console.WriteLine(Factorial(5));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate a factorial?
Start the product at 1 and multiply by every integer from 2 through n. Restrict the input to 0 through 20 because 21! exceeds the range of long.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.