Golang 如何找到一个数字的阶乘
在本教程中,我们将编写并解释在Golang中查找一个数字的阶乘的代码。阶乘是指数字与所有小于它的数字相乘的结果。在本教程中,我们将看到两种在Golang中寻找阶乘的方法。一种是通过创建一个递归函数。二是通过使用for a loop。
例如,5的阶乘是。
5! = 5 * 4 * 3 * 2 * 1
= 120
求一个数的阶乘的递归方法
算法
- 第1步- 在第1步中,我们要声明我们想要找出的阶乘的数字。数据类型是int64,这样我们也可以存储大阶乘值。
-
第2步 – 现在我们将从用户那里获得输入,并将其存储到我们上面声明的变量中。
-
第3步 – 现在我们将调用阶乘函数,该函数将通过递归地做乘法来寻找阶乘。
时间复杂度
O(N)
空间复杂度
O(1)
例子
在这个例子中,我们将创建一个递归函数,最后将返回该函数的阶乘。
package main
// fmt package provides the function to print anything
import "fmt"
func factorial(number int64) int64 {
// if the number has reached 1 then we have to
// return 1 as 1 is the minimum value we have to multiply with
if number == 1 {
return 1
}
// multiplying with the current number and calling the function
// for 1 lesser number
factorialOfNumber := number * factorial(number-1)
// return the factorial of the current number
return factorialOfNumber
}
func main() {
// declaring the integer number using the var keyword
// whose factorial we have to find
var number int64
// initializing the variable whose factorial we want to find
number = 10
// calling the factorial() function and printing the factorial
fmt.Println("The factorial of", number, "is", factorial(number))
fmt.Println("(Finding the factorial in a recursive manner.)")
}
输出
The factorial of 10 is 3628800
(Finding the factorial in a recursive manner.)
逻辑解释
让我们看看数字6的函数调用是如何发生的。
- 第一个调用的是阶乘(6),返回6*阶乘(5)。
-
现在在最后一个函数中调用了阶乘(5),返回5*阶乘(4)。
-
在最后一个函数中调用阶乘(4),返回4*阶乘(3)。
-
在最后一个函数中调用阶乘(3),即调用3*阶乘(2)。
-
在最后一个函数中调用阶乘(2),即调用2*阶乘(1)。
-
在最后一个函数中调用了阶乘(1),它将返回1作为匹配的基本条件,现在我们将以先进先出的方式进入最后一个函数调用。
-
现在,阶乘(2)将返回2*1=2
-
阶乘(3)返回 3 * 2 = 6
-
阶乘(4)返回 4 * 6 = 24
-
阶乘(5)返回5 * 24 = 120
-
阶乘(6)返回6 * 120 = 720
求一个数字的阶乘的循环方法
算法
-
第1步-- 在第1步中,我们要声明我们想要找出的阶乘的数字。数据类型是int64,这样我们也可以存储大阶乘值。
-
第2步 – 现在我们将从用户那里获得输入,并存储到我们上面声明的变量中。
-
第3步 – 现在我们将运行for循环来寻找阶乘。
例子
在这个例子中,我们将使用for循环来寻找用户输入的一个数字的阶乘。
package main
// fmt package provides the function to print anything
import "fmt"
func main() {
// declaring the integer number using the var keyword
// whose factorial we have to find
var number, iterator int64
// initializing the variable whose factorial we want to find
number = 9
// declaring the answer variable of int64 type and initializing with 1
var answer int64 = 1
// Running the for loop to find the factorial
for iterator = 1; iterator <= number; iterator++ {
answer = answer * iterator
}
// Printing the factorial of the respective number
fmt.Println("The factorial of", number, "is", answer)
fmt.Println("(Finding the factorial using for loop.)")
}
输出
The factorial of 9 is 362880
(Finding the factorial using for loop.)
逻辑解释
让我们看看如何使用for循环来寻找一个等于6的数字的阶乘。
- 在第一次迭代中,我们将答案乘以1,所以答案 = 1 * 1 = 1。
-
在第二次迭代中,我们将答案乘以2,所以答案=1*2=2。
-
在第三次迭代中,我们将答案乘以3,所以答案=2*3=6。
-
在第四次迭代中,我们将答案乘以4,所以答案=6*4=24。
-
在第五次迭代中,我们将答案乘以5,所以答案=24*5=120。
-
在第六次迭代中,我们将答案乘以6,所以答案=120*6=720。
结论
这就是我们如何找到6的值!即用for循环找到720。这就是寻找一个数字的阶乘的两种不同方法。