Friday, 6 December 2013

Find factorial of a number in Java?

There are two ways to find factorial of a number. One is iterative which is very simple and other is recursive. Following is the code to get factorial by recursive method.

Code :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<b>/**
 * Created with IntelliJ IDEA.
 * User: aniket
 * Date: 6/12/13
 * Time: 2:52 PM
 * To change this template use File | Settings | File Templates.
 */
public class FactorialFinder {
 
    public static int factorial(int no){
 
        if(no < 0){
            throw new RuntimeException("Number cannot be Negative");
        }
        else if(no == 1){
            return no;
        }
        else{
            return no * factorial(no - 1);
        }
 
    }
 
    public static void main(String args[]){
        int number = 4;
        System.out.printf("Factorial of 4 is : " + FactorialFinder.factorial(4));
    }
 
 
}
</b>

Output

Factorial of 4 is : 24

No comments:

Post a Comment

t> UA-39527780-1 back to top