首页 > 解决方案 > NchooseR Java 递归程序

问题描述

当用户输入两个数字时,我在查找“NChooseR”值时遇到问题,并且程序必须使用递归。"NchooseR" 公式必须是n! / r!(n-r)!

Scanner input = new Scanner(System.in);

    System.out.println("This program will calculate the number of ways to chose r different objects from a set of n objects\n");

    System.out.println("How many objects would you  like to chose? (r value)");
    int userR = input.nextInt();

    System.out.println("How many objects are there to chose from? (n value)");
    int userN = input.nextInt();

    System.out.println("There are " + nchooser(userN, userR) + " ways to chose " + userR + " objects from a set of " + userN + " objects");

}

public static long factorialn(int n) {
    //return a value of one for terms one and two
    if ((n == 1) || (n == 2)) {
        return 1;

    } else {
        return factorialn(n - 1) + factorialn(n - 2);
    }
}

public static long factorialr(int r) {
    //return a value of one for terms one and two
    if ((r == 1) || (r == 2)) {
        return 1;

    } else {
        return factorialr(r - 1) + factorialr(r - 2);
    }
}

    public static long factorialnr(int r, int n) {
    //return a value of one for terms one and two
    if ((r == 1) || (r == 2) || (n == 1) || (n == 2)) {
        return 1;

    } else {
        return factorialr((n-r) - 1) + factorialr((n - r) - 2);
    }
}

public static long nchooser(int r, int n) {


    return factorialn(n) / (factorialr(r) * (factorialnr(n,r)));
}

标签: javarecursion

解决方案


这是一些可能适用于更大数字的代码:

public static final long f(final int n) { // factorial
    long i,p;
    if(n<=1)
        p=1;
    else for(p=n,i=2;i<=n-1;i++)
        p=p*i;
    return (p);
}
public static final long c(final int n,final int r) { // binomial coefficient
    long i,p;
    if(r<0||n<0||r>n)
        p=0;
    else if(r==0)
        p=1;
    else if(r>n-r)
        p=c(n,n-r);
    else {
        for(p=1,i=n;i>=n-r+1;i--)
            p=p*i;
        p=p/f(r);
    }
    return p;
}

推荐阅读