March 02, 2015

How to find factorial of a number using recursion in java


How to Find Factorial of a number using recursion in java


/**
 * How to find factorial of a number using recursion, while loop and for loop
 */

/**
 * @author Samsung Galaxy
 *
 */
public class Factorial {

private int usingRecursion(int num) {
// TODO Auto-generated method stub
int result =1;
if(num==1){
return 1;
}
result = usingRecursion(num-1) * num;
return result;
}

private int usingWhileLoop(int num) {
// TODO Auto-generated method stub
int result =1;
while(num>1){
result = result * num;
num = num -1;
}

return result;
}


private int usingForLoop(int num) {
int result =1;
for(int value=2;value<=num;value++){
result = result * value;
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int inputValue =4;
Factorial factorial = new Factorial();
int number = factorial.usingRecursion(inputValue);
int numb = factorial.usingWhileLoop(inputValue);
int numbr = factorial.usingForLoop(inputValue);
System.out.println("Factorial using recursion method is : "+number +", using while loop is : "+numb+" and using for loop is : "+numbr);

}

}

Output



Source code java Factorial
Factorial in Java


About Fibonacci Sequence

The Fibonacci Series is a series of number where the next number is found by adding up last two number in the series.

Series : 0,1,1,2,3,5,8,13,21,34 and so on

Fibonacci Number, their ration is very close to Golden ration "phi" which is equal to 1.618.

Real world example : Fibonacci considers the growth of shell of snail


http://javabelazy.blogspot.in/

Facebook comments