Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic recursive method - factorial

I am practicing recursion and I can't see why this method does not seem to work. Any ideas?

    public void fact()
    {
        fact(5);
    }

    public int fact(int n)
    {
        if(n == 1){
            return 1;
        }
        return n * (fact(n-1));
    }
}

Thanks

like image 773
bob Avatar asked Dec 06 '22 02:12

bob


2 Answers

Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.

like image 116
Anthony Forloney Avatar answered Dec 19 '22 11:12

Anthony Forloney


The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:

public class Factorial {
    public static String fact(int n) {
        if(n == 1){
            return "1";
        }
        return n + " * " + (fact(n-1)); // what happens if you switch the order?
    }
    public static void main(String[] args) {
        System.out.println(fact(5));
        // prints "5 * 4 * 3 * 2 * 1"
    }
}
like image 32
polygenelubricants Avatar answered Dec 19 '22 12:12

polygenelubricants