博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
scala 数字阶乘_Scala程序查找数字的阶乘
阅读量:2534 次
发布时间:2019-05-11

本文共 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,

程序将使用此公式查找阶乘。 发现阶乘是一个重复的过程。 我们有两种方法可以解决此问题,

  1. Using iteration

    使用迭代

  2. Using recursion

    使用递归

1)递归方法查找数字的阶乘 (1) Recursive Approach to find factorial of a number)

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

2)迭代方法来找到数字的阶乘 (2) Iterative approach to find factorial of a number)

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/

你可能感兴趣的文章
IOS内存管理
查看>>
我需要一个足够大的桌子
查看>>
middle
查看>>
[Bzoj1009][HNOI2008]GT考试(动态规划)
查看>>
Blob(二进制)、byte[]、long、date之间的类型转换
查看>>
linux awk命令详解
查看>>
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
交换机划分Vlan配置
查看>>