Question

Permutation with BigInteger works fine upto 4 digits (3456 P 1234) when i give 5 digit input to n and r, it is not working. i have changed my input type as BigInteger n = scan.nextBigInteger();I edited my code as

`

    import java.math.BigInteger;
    import java.util.Scanner;

    public class cvic {
 public static void main(String[] args)
{   
Scanner scan = new Scanner(System.in);
System.out.print("Enter n and r: ");
BigInteger n = scan.nextBigInteger();
BigInteger r = scan.nextBigInteger();

System.out.println("nPr = "+fact(n).divide(fact(n.subtract(r))));
}
 static BigInteger fact(BigInteger num) {        
 BigInteger fa = BigInteger.ONE;      
for(BigInteger inte = BigInteger.ONE; inte.compareTo(num) <= 0; inte = inte.add(BigInteger.ONE)){            
fa = fa.multiply(inte);
    }        
    return fa;
    }
          }

`

Was it helpful?

Solution 2

You have an endless for loop, so your application never ends.

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;
}

OTHER TIPS

You have an infinite loop in your program:

for(inte.equals(1);inte.compareTo(BigInteger.ZERO)>=0;inte.add(BigInteger.ONE))
  • inte.equals(1) always evaluates to true and as a bonus does nothing.
  • inte.compareTo(BigInteger.ZERO) >= 0 is always true (that's why the for loop will never terminate) because inte is always equal to 1
  • inte.add(BigInteger.ONE) - returns a new BigInteger and doesn't modify inte (BigInteger is an immutable class) - hence inte will always be equal to 1.

What you want is probably (I assume what you want is: calculate a factorial of bv):

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

Correct handling of fact(0) is left as an exercise for the reader.

You need to bound your for loop by bv instead of zero. Also, you need to increment inte properly, as suggested in another answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top