Вопрос

I need to write a method that does n!/(n-r)!. This would be easy to do in a for loop but I can't figure it out recursively. Here is my code so far.

public static int permut(int n, int r) {
    if (r == 0) {
        return 0;
    } else if (r==1){
        return n;
    } else {    
        return n * permut(n, r-1)/permut(n,r-1);
    }
}

I am not sure how to setup the return.

Это было полезно?

Решение

Essentially, you can think of this the same as a normal factorial, accept that you decrement n and r each recursion and stop when r == 1 instead of n == 1.

public static int permut(int n, int r){
    if(r == 1) return n;
    return n*permut(n-1, r-1);
}

So if n = 10 and r = 3, you need 10!/(10-3)! or 10*9*8, and the program will give:

n = 10, r = 3, val = 10
n = 9,  r = 2, val = 10*9
n = 8,  r = 1, val = 10*9*8
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top