7
private static int chain(int n){
        int count = 0;
        while(n > 1){
            if(n % 2 == 0){
                count++; //the value is not stored
                return chain(n/2);
            }
            count++; //same thing
            return chain(3*n+1);
        }
        return count; //prints the initial value (0)
    }
}

我需要打印链方法再次发生的次数。

4

4 回答 4

10

How about this:

public static int chain(int n) {
    return chain(n, 0);
}

private static int chain(int n, int count) {
    if (n > 1) {  // no need for a while-loop, it will never get past 1 iteration
        if (n % 2 == 0) {
            return chain(n / 2, count + 1);
        }
        return chain(3 * n + 1, count + 1);
    }
    return count;
}

To me, this seems cleaner than declaring a static field outside of the method, primarily because I wouldn't want to worry about having to reset the static field to 0 every time I call chain.

于 2013-04-18T14:10:14.593 回答
5

我真的不明白你在问什么。但是如果你想让 count 存在于方法之外,而不是每次调用方法时都创建一个本地副本,你可以将其设为静态。

static int count=0;
于 2013-04-18T14:05:03.493 回答
4

从您的方法中删除count变量,并使其成为您的类的静态成员。并且为了防止重复 yourlsef(DRY 原则),您应该count在方法顶部增加变量。

private static int count = 0;

private static int chain(int n) {
    count++;

    while(n > 1) {
        if(n % 2 == 0) {
            return chain(n/2);
        }

        return chain(3*n+1);
    }

return count;
}
于 2013-04-18T14:13:36.063 回答
1

这似乎也有效,并且不使用那个丑陋的额外参数。

我已经稍微调整了算法(chain(3 * n + 1)加入了else一部分),假设这实际上是在尝试测量Collat​​z 猜想的冰雹序列的长度。正如最初所说,它只会堆栈溢出。

111这段代码在通过时确实会产生27

private static int recursiveChain(int n) {
  if (n > 1) {
    if (n % 2 == 0) {
      return 1 + recursiveChain(n / 2);
    } else {
      return 1 + recursiveChain(3 * n + 1);
    }
  } else {
    return 0;
  }
}

迭代版本看起来与原始问题惊人地相似:

private static int iterativeChain(int n) {
  int count = 0;
  while (n > 1) {
    count += 1;
    if (n % 2 == 0) {
      n = n / 2;
    } else {
      n = 3 * n + 1;
    }
  }
  return count;
}
于 2013-04-18T14:22:33.470 回答