bigIntegerFakultaet.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import javax.swing.JOptionPane;
  2. import java.util.Arrays;
  3. import flanagan.io.Db;
  4. import java.math.BigInteger;
  5. public class bigIntegerFakultaet {
  6. public static void main(String [] args) {
  7. // init variables
  8. int factorial = 0;
  9. BigInteger res = BigInteger.valueOf(1);
  10. BigInteger resn = BigInteger.valueOf(1);
  11. // get factorial input
  12. try {
  13. factorial = Db.readInt("factorial = ");
  14. } catch (NumberFormatException e) {
  15. Db.show("Error: no valid integer input provided");
  16. System.exit(1);
  17. }
  18. // validate that: factorial >= 0
  19. if (factorial < 0) {
  20. Db.show("Error: input cannot be negative");
  21. System.exit(1);
  22. }
  23. // print top table row
  24. System.out.format("n \tn!\n\n");
  25. // special case: 0! = 1
  26. if (factorial == 0) {
  27. System.out.format("%d \t%d (%d-digit)\n", 0, 1, res.toString().length());
  28. System.exit( 0 );
  29. }
  30. // use big integer
  31. BigInteger bigFactorial = BigInteger.valueOf(factorial);
  32. for (BigInteger n = BigInteger.valueOf(1); n.compareTo(bigFactorial) <= 0; n = n.add(BigInteger.ONE))
  33. {
  34. res = n.multiply(resn); // current result
  35. resn = res; // new overall result
  36. System.out.format("%d \t%d (%d-digit)\n", n, res, res.toString().length());
  37. }
  38. }
  39. }