如何以较少复杂的方式使用BigInteger?

时间:2017-02-14 21:16:19

标签: java biginteger

所以在写完这个问题的标题后,我意识到我只需要声明一个BigInteger变量,并且可以将它作为函数参数和返回变量使用(这是它的调用方式吗?)

public static void ex8(){
    double time_duration = 0;
    BigInteger fact; // Originally I also had an "arg" BigInteger

    long l = 100000;
    fact = BigInteger.valueOf(l); //I had arg = (...) instead of fact

    double time_before = System.currentTimeMillis();
    //originally it was fact = Matematica.factorial(arg);
    fact = Matematica.factorial(fact);
    double time_after = System.currentTimeMillis();

    time_duration = time_after - time_before;

    System.out.println("Execution time: " + time_duration + " ms " + "AND\n" + "Factorial result: " + fact);  
}

因此,如果我想使用BigInteger,我似乎必须:

  • 声明BigInteger变量
  • 声明一个长变量
  • 将长变量转换为(?)BigInteger并将其赋值为
  • 正常使用

问题:有什么办法可以简化这个过程吗?任何方式我都可以正常使用BigInteger而无需转换东西?

3 个答案:

答案 0 :(得分:1)

在将变量作为参数传递给BigInteger.valueOf之前,您不需要在变量中加长 - 您可以将其内联。

我认为您提供的代码最干净的编辑如下。请注意,时间戳已更改为长类型声明,并且不会重用事实变量。

public static void ex8(){
    BigInteger num = BigInteger.valueOf(100000L); 

    long time_before = System.currentTimeMillis();
    BigInteger fact = Matematica.factorial(num);
    long time_after = System.currentTimeMillis();

    long time_duration = time_after - time_before;

    System.out.println("Execution time: " + time_duration + " ms " + "AND\n" + "Factorial result: " + fact);
}

答案 1 :(得分:0)

感谢我提交的评论,因为没有人在主帖上没有正确回答,我会自己发布。

BigInteger fact = new BigInteger("10000");
OR
BigInteger fact = BigInteger.valueOf(100000L);

所以它变成

 public static void ex8(){
    double time_duration = 0;
    BigInteger fact = new BigInteger("10000");


    double time_before = System.currentTimeMillis();
    fact = Matematica.factorial(fact);
    double time_after = System.currentTimeMillis();

    time_duration = time_after - time_before;

    System.out.println("Execution time: " + time_duration + " ms " + "AND\n" + "Factorial result: " + fact);  
}

好多了。感谢

答案 2 :(得分:-2)

您可以用这种方式声明和初始化BigInteger变量:

scrollLogic