本文共 1942 字,大约阅读时间需要 6 分钟。
scala 数字阶乘
Factorial of a number(n!) is the product of all positive numbers less than or equal to that number.
数字的阶乘(n!)是所有小于或等于该数字的正数的乘积。
The formula for factorial of a number is,
数字阶乘的公式是,
n! = n * (n-1) * (n-2) * ... * 2 * 1 n! = 1 if n = 1 or 0
Based on the above formula we can generate a recursive formula,
根据上述公式,我们可以生成一个递归公式,
n! = n * (n-1)!
Given a number, we have to find its factorial.
给定一个数字,我们必须找到它的阶乘。
Example:
例:
Input: n = 6 Output: n! = 720 Explanation: 6! = 6*5*4*3*2*1 = 720
The program will use this formula to find the factorial. As find factorial is a repetitive process. We have two methods to solve this problem,
程序将使用此公式查找阶乘。 发现阶乘是一个重复的过程。 我们有两种方法可以解决此问题,
Using iteration
使用迭代
Using recursion
使用递归
In recursion, we will call the same method multiple times until a condition is not satisfied.
在递归中,我们将多次调用同一方法,直到不满足条件为止。
Here, we will call the function factorial(n) in the following way:
在这里,我们将通过以下方式调用函数factorial(n) :
Program:
程序:
object myObject { def factorialRec(n: Int): Int ={ if(n <= 1) return 1 return n * factorialRec(n-1) } def main(args: Array[String]) { val n = 6 println("The factorial of " + n + " is " + factorialRec(n)) }}
Output
输出量
The factorial of 6 is 720
In iteration, we will loop over a sequence of numbers and multiply the number to result variable to find factorial.
在迭代中,我们将遍历数字序列,并将数字乘以结果变量以找到阶乘。
Program:
程序:
object myObject { def factorialIt(n: Int): Int ={ var factorial = 1 for(i <- 1 to n) factorial *= i return factorial } def main(args: Array[String]) { val n = 6 println("The factorial of " + n + " is " + factorialIt(n)) }}
Output
输出量
The factorial of 6 is 720
翻译自:
scala 数字阶乘
转载地址:http://ecvzd.baihongyu.com/