Today, the AI written test question tool we developed, ai Bianshi - the AI programmer written test system, gave me an intermediate Golang question, which is this question: " Please write a function that receives an integer parameter n and outputs the factorial result of n" , I hope I can write a function that outputs the factorial result of n. I didn't think there was any problem at first, so I probably wrote an implementation as follows:
// 循环计算n的阶乘
func factorial(n int) int {
var result = 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
Or you can use recursion:
// 计算n的阶乘
func factorial1(n int) int {
if n == 1 {
return 1
}
return n * factorial1(n-1)
}
Later I felt something was wrong. It didn’t look like an intermediate question.
I ran a simple test example and found that these two implementations actually overflowed int at 21.
21的阶乘是-4249290049419214848
21的阶乘是-4249290049419214848
Oh, sure enough there is a hidden test point.
Golang actually provides us with a large number library:
math.Big
The loop implementation version of the Big library is as follows:
// 计算n的阶乘,使用math/big包
func factorial3(n int) *big.Int {
var result = big.NewInt(1)
for i := 1; i <= n; i++ {
result.Mul(result, big.NewInt(int64(i)))
}
return result
}
or recursive version
// 计算n的阶乘,使用math/big包,递归实现
func factorial8(n int) *big.Int {
if n == 1 {
return big.NewInt(1)
}
var result = big.NewInt(int64(n))
return result.Mul(result, factorial8(n-1))
}
Finally, I chose to submit the loop version. The recursive version has unnecessary consumption when the recursion depth is deep, so looping is fine.