Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 大整数置换_Java_Loops_For Loop_Biginteger - Fatal编程技术网

Java 大整数置换

Java 大整数置换,java,loops,for-loop,biginteger,Java,Loops,For Loop,Biginteger,使用BigInteger的置换可以很好地工作到4位(3456 p 1234)。当我给n和r输入5位数字时,它不工作。我已将输入类型更改为biginger n=scan.nextbiginger()我将代码编辑为 ` import java.math.biginger; 导入java.util.Scanner; 公共类cvic{ 公共静态void main(字符串[]args) { 扫描仪扫描=新扫描仪(System.in); 系统输出打印(“输入n和r:”); BigInteger n=s

使用
BigInteger
的置换可以很好地工作到4位(3456 p 1234)。当我给n和r输入5位数字时,它不工作。我已将输入类型更改为
biginger n=scan.nextbiginger()我将代码编辑为

`

import java.math.biginger;
导入java.util.Scanner;
公共类cvic{
公共静态void main(字符串[]args)
{   
扫描仪扫描=新扫描仪(System.in);
系统输出打印(“输入n和r:”);
BigInteger n=scan.nextBiginger();
BigInteger r=scan.nextBiginger();
System.out.println(“nPr=“+事实(n).除(事实(n.减去(r))));
}
静态BigInteger事实(BigInteger num){
biginger fa=biginger.ONE;

对于(biginger inte=biginger.ONE;inte.compareTo(num),程序中有一个无限循环:

for(inte.equals(1);inte.compareTo(BigInteger.ZERO)>=0;inte.add(BigInteger.ONE))
  • inte.equals(1)
    的计算结果总是
    true
    ,作为奖金,它什么也不做
  • inte.compareTo(BigInteger.ZERO)>=0
    总是
    true
    (这就是为什么
    for
    循环永远不会终止的原因),因为
    inte
    总是等于1
  • integer.add(biginger.ONE)
    -返回一个新的
    biginger
    ,并且不修改
    inte
    biginger
    是一个不可变的类)-因此
    inte
    将始终等于1
您想要的可能是(我假设您想要的是:计算
bv
的阶乘):


while(inte.compareTo(bv)您有一个无尽的for循环,所以您的应用程序永远不会结束

static BigInteger fact(BigInteger bv) {        
    BigInteger fa = BigInteger.ONE;      
    for(BigInteger inte = BigInteger.ONE; inte.compareTo(bv) <= 0; inte = inte.add(BigInteger.ONE)){            
        fa = fa.multiply(inte);
    }        
    return fa;
}
静态BigInteger事实(BigInteger bv){
biginger fa=biginger.ONE;

对于(biginger inte=biginger.ONE;inte.compareTo(bv)您需要通过
bv
而不是零来绑定for循环。此外,您还需要按照另一个答案中的建议正确地递增
inte

“我的代码不起作用”信息永远都不够。你至少需要告诉我们预期结果和实际结果。你还应该编辑你的帖子,使其格式正确。你在程序启动时输入整数了吗?是的,我可以输入,之后什么都不会发生。
for(inte.equals(1)s@Trenin,没关系。Kruthika,我用我的example@Kruthika好的-很抱歉我的评论语气。也可以是(inte=biginger.ONE;inte.compareTo(bv)的

while (inte.compareTo(bv) <= 0) {
  fa = fa.multiply(inte);
  inte = inte.add(BigInteger.ONE);
}
static BigInteger fact(BigInteger bv) {        
    BigInteger fa = BigInteger.ONE;      
    for(BigInteger inte = BigInteger.ONE; inte.compareTo(bv) <= 0; inte = inte.add(BigInteger.ONE)){            
        fa = fa.multiply(inte);
    }        
    return fa;
}