java - Factorial using recursion -


class {   int fact(int n) { if (n==1)    return 1; else     return fact(n-1)*n; }  } class b {  public static void main(string a[]) {     f=new a();     system.out.println("fact of 5 is"+f.fact(5)); }  } 

recursion approach aims solve problems finding pattern while solving problem! know finding factorial of number n multiplying number factorial of n-1 . thus

6!= 6 * 5! 

or,

fact(n)= n * fact(n-1) 

now cause

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

every step decrements n , stop when encounter 1 or 0 in case return 1

finally compiler uses value of fact(1) compute fact(2) in turn computes fact(3) retracing way number factorial desired

recursion though more elegant & suitable strain on memory(read activation records,stacks in recursion) because functions called recursively stored till function exits. problem eliminated using tail recursion or not employing recursion @ all


Comments