简体   繁体   中英

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 . 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

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

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). In that case control will go to the else block and again it will return and call fact(5) and so on. So there will not be an end of this method call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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