Saturday, October 20, 2012

Mathematics8

Q8. Write a method to get factorial of given integer? Try both recursive and iterative method.
Answer: 

public class Mathematics8 {
    public static int factorialRecursive(int n) {
        if (n < 0) {
            System.out.println("Factorial is not defined for negative numbers");
            return 0;
        }

        if (n == 0) {
            return 1;
        }
        return n * factorialRecursive(n - 1);
    }

    public static int factorialIterative(int n) {
        if (n < 0) {
            System.out.println("Factorial is not defined for negative numbers");
            return 0;
        }

        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact *= i;
        }
        return fact;
    }

    public static void main(String[] args) {
        System.out.println(factorialRecursive(0));
        System.out.println(factorialRecursive(-11));
        System.out.println(factorialRecursive(5));
        System.out.println(factorialRecursive(10));

        System.out.println(factorialIterative(0));
        System.out.println(factorialIterative(-11));
        System.out.println(factorialIterative(5));
        System.out.println(factorialIterative(10));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.