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 :


/**
 * 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));
    }


}

Output

Factorial of 4 is : 24

No comments:

Post a Comment

t> UA-39527780-1 back to top