它的java代码显示了此代码中的算术异常我该如何解决它?

时间:2016-03-11 11:20:37

标签: java algorithm open-source project

import java.util.*;

public class E53 {
  int l = 0;

  public int fact(int x) {
    if (x != 1) l = x * fact(x - 1);
    return l;
  }

  public static void main(String... s) {
    int count = 0;
    E53 e = new E53();

    for (int n = 23; n < 100; n++) {
      for (int r = 2; r + 1 < n; r++) {
        int c = (e.fact(n) / (e.fact(r) * e.fact(n - r)));
        if (c > 100000) count++;
        System.out.println(count);
      }
    }
  }
}

2 个答案:

答案 0 :(得分:3)

您的因子实施是错误的。不要使用实例变量(l)来存储该方法的结果。

目前它返回0,因为当x==1时,你返回l,它被初始化为0,所以fact(1)返回0,fact(2) == 2 * fact(1) == 2 * 0 == 0并且也返回0,所以上。

您不需要fact方法中的任何变量:

public int fact(int x)
{   
    if(x>1)
         return x*fact(x-1);
    else
         return 1;
}

编辑:

正如Peter和Andy评论的那样,此更改仅修复了部分问题,因为在使用int类型时,无法计算大整数的阶乘,因为2^31-1类型仅限于double。使用BigIntegerint代替 import sys from PyQt4 import QtCore, QtGui from SerialMonitor import Ui_SerialMonitor class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_SerialMonitor() self.ui.setupUi(self) QtCore.QObject.connect(self.ui.readButton,QtCore.SIGNAL("clicked()"),self.startReading) QtCore.QObject.connect(self.ui.stopButton, QtCore.SIGNAL("clicked()"),self.stopReading) def startReading(self): print("1") self.ui.stopButton.isEnabled(False) def stopReading(self): print("2") self.ui.readButton.isEnabled(True) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = StartQT4() myapp.show() sys.exit(app.exec_()) 将允许您的代码适用于您计算因子的整个数字范围。

答案 1 :(得分:0)

加快速度并简化它。

import java.util.stream.IntStream;

public enum E35 {
    ; // no instances

    public static double fact(int n) {
        return n <= 1 ? 1 : n * fact(n - 1);
    }

    public static double comb(int n, int r) {
        return n <= r ? 1 : n * comb(n - 1, r);
    }

    public static void main(String... args) {
        long start = System.currentTimeMillis();
        long count = IntStream.range(23, 100)
                .parallel()
                .mapToLong(n -> IntStream.range(2, n - 1)
                        .filter(r -> comb(n, r) / fact(n - r) > 1e5)
                        .count())
                .sum();
        long time = System.currentTimeMillis() - start;
        System.out.println(count+" took "+time/1e3+" seconds");
    }
}

打印

4138 took 0.07 seconds