PowerShell Script to Find Factorial of a Number
$factorial = 1; for ($i = 1; $i -le $n; $i++) { $factorial *= $i } to calculate the factorial of a number stored in $n.Examples
How to Think About It
Algorithm
Code
$n = Read-Host 'Enter a non-negative integer' $factorial = 1 for ($i = 1; $i -le $n; $i++) { $factorial *= $i } Write-Output "Factorial of $n is $factorial"
Dry Run
Let's trace the input 5 through the code
Initialize
$factorial = 1, $i = 1
First loop iteration
$factorial = 1 * 1 = 1
Second loop iteration
$factorial = 1 * 2 = 2
Third loop iteration
$factorial = 2 * 3 = 6
Fourth loop iteration
$factorial = 6 * 4 = 24
Fifth loop iteration
$factorial = 24 * 5 = 120
| Iteration | Value of i | Factorial |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 6 |
| 4 | 4 | 24 |
| 5 | 5 | 120 |
Why This Works
Step 1: Start with 1
We set $factorial to 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply step by step
Each loop multiplies $factorial by the current number $i, building the factorial product gradually.
Step 3: Loop until input number
The loop runs until it reaches the input number, ensuring all numbers from 1 to $n are included in the multiplication.
Alternative Approaches
function Get-Factorial($n) { if ($n -le 1) { return 1 } else { return $n * (Get-Factorial ($n - 1)) } } $n = Read-Host 'Enter a non-negative integer' $result = Get-Factorial $n Write-Output "Factorial of $n is $result"
Add-Type -AssemblyName System.Numerics function Get-FactorialBig([int]$n) { $result = [System.Numerics.BigInteger]::One for ($i = 1; $i -le $n; $i++) { $result = $result * $i } return $result } $n = Read-Host 'Enter a non-negative integer' $result = Get-FactorialBig $n Write-Output "Factorial of $n is $result"
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so the time grows linearly with the input number.
Space Complexity
Only a few variables are used, so space stays constant regardless of input size.
Which Approach is Fastest?
The iterative loop is fastest and uses less memory than recursion, which adds call stack overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | General use, efficient |
| Recursive function | O(n) | O(n) | Elegant code, small inputs |
| .NET BigInteger loop | O(n) | O(1) | Very large numbers |