简体   繁体   English

使用递归的阶乘

[英]Factorial using recursion

Class A {

 Int fact(int n)
{
If (n==1)
   Return 1;
Else 
   Return fact(n-1)*n;
}

}
Class B {

Public static void main(String a[])
{
    A f=new A();
    System.out.println("fact of 5 is"+f.fact(5));
}

}

Recursion approach aims to solve problems by finding a pattern while solving a problem!递归方法旨在通过在解决问题的同时找到模式来解决问题! We know for finding a factorial of a number n we would get it easily by multiplying the number with factorial of n-1 .我们知道要找到一个数 n 的阶乘,我们可以通过将这个数乘以 n-1 的阶乘来轻松得到它。 Thus因此

6!= 6 * 5!

OR,或者,

Fact(n)= n * Fact(n-1)

Now This would cause现在这会导致

Fact(6)= 6 * Fact(5);
           = 6 * (5 * Fact(4));

Every step decrements n and we stop this when we encounter 1 or 0 in whose case we simply return 1每一步都递减 n,当我们遇到 1 或 0 时,我们就停止它,在这种情况下,我们只返回 1

Finally the compiler uses the value of Fact(1) to compute Fact(2) which in turn computes Fact(3) retracing all the way back to the number whose factorial is desired最后,编译器使用 Fact(1) 的值来计算 Fact(2),后者又计算 Fact(3) 一直回溯到需要阶乘的数字

Recursion though often more elegant & suitable is a strain on memory(read about activation records,stacks in Recursion) because everything about the functions called recursively is stored till the function exits.递归虽然通常更优雅且更合适,但它会占用内存(阅读关于活动记录、递归中的堆栈),因为有关递归调用的函数的所有内容都存储到函数退出为止。 This problem could be eliminated by using tail Recursion or not employing Recursion at all这个问题可以通过使用尾递归或根本不使用递归来消除

As per your statement following code will return the same result :根据您的声明,以下代码将返回相同的结果:

Class A{

Int fact(int n)

{ If (n==1)

Return 1;

Else

Return fact(n);

}

} Class B {

Public static void main(String a[])

{

A f=new A();

System.out.println("fact of 5 is"+f.fact(5));

}

}

But, suppose you are calling fact(5).但是,假设您正在调用 fact(5)。 In that case control will go to the else block and again it will return and call fact(5) and so on.在这种情况下,控制将转到 else 块,它会再次返回并调用 fact(5) 等等。 So there will not be an end of this method call.所以这个方法调用不会结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM