1

我似乎无法弄清楚这一点。我需要计算给定数字以下有多少个数字可以整除。

这是我尝试过的:

public int testing(int x) {
    if (x == 0) {
        System.out.println("zero");
        return x;
    }
    else if ((x % (x-1)) == 0) {
        System.out.println("does this work?");
        x--;
    }

    return testing(x-1);
}

那行不通,我不知道从这里去哪里。有谁知道该怎么做?

4

6 回答 6

2

这是错误的:

 public int testing(int x) {

如果要使其递归,则需要同时传递要测试的数字和当前正在检查的数字。第一个不会通过递归改变,第二个会递减。你不能只用一个参数来做你表达的事情(除非你使用一个全局变量)。

于 2013-10-04T23:29:22.227 回答
2

这不是一个应该用递归来解决的任务。

如果你必须使用递归,最简单的方法是有第二个参数,它本质上是一个“我已经检查到这个数字”。然后你可以增加/减少这个(取决于你是从 0 开始还是从初始数字开始)并在上面调用递归。

问题是,Java 不是一种函数式语言,所以做这一切实际上有点愚蠢,所以给你做这个练习的人可能需要头脑清醒。

于 2013-10-05T00:19:21.257 回答
0

您的问题是您的表达式x % (x - 1)正在使用 的“当前”值x,该值在每次调用递归函数时都会递减。你的条件一直是假的2 % (2 - 1)

使用for循环是处理此任务的更好方法(并查看 Eratosthenes 的筛子),但如果您真的必须使用递归(对于家庭作业),您需要传入被分解的原始值以及正在尝试的当前值。

于 2013-10-04T23:26:45.737 回答
0

你的算法有问题。请注意,递归仅在 x == 0 时结束,这意味着您的函数将始终返回 0(如果它完全返回)。

此外,您的算法似乎没有任何意义。您基本上是在尝试找到一个数字的所有因数,但只有一个参数 x。

尝试为您的变量取有意义的名称,这样逻辑将更易于阅读/遵循。

public int countFactors(int number, int factorToTest, int numFactors)
{
  if (factorToTest == 0) // now you are done
    return numFactors;
  else
    // check if factorToTest is a factor of number
    // adjust the values appropriately and recurse
}
于 2013-10-04T23:29:05.007 回答
0

这里不需要使用递归。这是一个非递归的解决方案:

public int testing(int n) {
    int count = 0;
    for (int i = 1; i < n; i++)
        if (n % i == 0)
            count++;
    return count;
}

顺便说一句,您可能应该将其称为testing.

于 2013-10-04T23:29:45.073 回答
0

使用递归:

private static int getFactorCount(int num) {
    return getFactorCount(num, num - 1);
}

private static int getFactorCount(int num, int factor) {
    return factor == 0 ? 0 : (num % factor == 0 ? 1 : 0)
            + getFactorCount(num, factor - 1);
}   

public static void main(String[] args) {
    System.out.println(getFactorCount(20)); // gives 5
    System.out.println(getFactorCount(30)); // gives 7
}
于 2013-10-05T00:03:55.203 回答