Go Program to Find Factorial of a Number
for i := 1; i <= n; i++ { result *= i }.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { var n int fmt.Print("Enter a number: ") fmt.Scan(&n) result := 1 for i := 1; i <= n; i++ { result *= i } fmt.Printf("Factorial of %d is %d\n", n, result) }
Dry Run
Let's trace the input 5 through the code
Input
User enters n = 5
Initialize result
result = 1
Loop start
i = 1, result = 1 * 1 = 1
Loop iteration 2
i = 2, result = 1 * 2 = 2
Loop iteration 3
i = 3, result = 2 * 3 = 6
Loop iteration 4
i = 4, result = 6 * 4 = 24
Loop iteration 5
i = 5, result = 24 * 5 = 120
Loop ends
i > n, exit loop
Print result
Output: Factorial of 5 is 120
| i | result |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
Why This Works
Step 1: Start with 1
We set result to 1 because multiplying by 1 does not change the value and it is the identity for multiplication.
Step 2: Multiply in loop
We multiply result by each number from 1 to n to accumulate the factorial product.
Step 3: Print final result
After the loop, result holds the factorial, which we print with the input number.
Alternative Approaches
package main import "fmt" func factorial(n int) int { if n == 0 { return 1 } return n * factorial(n-1) } func main() { var n int fmt.Print("Enter a number: ") fmt.Scan(&n) fmt.Printf("Factorial of %d is %d\n", n, factorial(n)) }
package main import ( "fmt" "math/big" ) func main() { var n int64 fmt.Print("Enter a number: ") fmt.Scan(&n) result := big.NewInt(1) for i := int64(1); i <= n; i++ { result.Mul(result, big.NewInt(i)) } fmt.Printf("Factorial of %d is %s\n", n, result.String()) }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs from 1 to n, so the time grows linearly with n, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
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) | Small to medium numbers, fast and simple |
| Recursive function | O(n) | O(n) | Simple code, but uses more memory and risks stack overflow |
| big.Int for large numbers | O(n) | O(1) plus big.Int memory | Very large numbers without overflow |