bigIntegerFakultaet.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. System.out.println("factorial input = " + factorial);
  15. } catch (NumberFormatException e) {
  16. Db.show("Error: no valid integer input provided");
  17. System.exit(1);
  18. }
  19. // print dashes
  20. for (int i = 0; i < 80; i++) {
  21. System.out.format("-");
  22. }
  23. System.out.println();
  24. // validate that: factorial >= 0
  25. if (factorial < 0) {
  26. Db.show("Error: input cannot be negative");
  27. System.exit(1);
  28. }
  29. // print top table row
  30. System.out.format("n \tn!\n");
  31. // print dashes
  32. for (int i = 0; i < 80; i++) {
  33. System.out.format("-");
  34. }
  35. System.out.println();
  36. // special case: 0! = 1
  37. if (factorial == 0) {
  38. System.out.format("%d \t%d (%d-digit)\n", 0, 1, res.toString().length());
  39. System.exit( 0 );
  40. }
  41. // use big integer
  42. BigInteger bigFactorial = BigInteger.valueOf(factorial);
  43. for (BigInteger n = BigInteger.valueOf(1); n.compareTo(bigFactorial) <= 0; n = n.add(BigInteger.ONE)) {
  44. res = n.multiply(resn); // current result
  45. resn = res; // new overall result
  46. System.out.format("%d \t%d (%d-digit)\n", n, res, res.toString().length());
  47. }
  48. // print dashes
  49. for (int i = 0; i < 80; i++) {
  50. System.out.format("-");
  51. }
  52. System.out.println();
  53. System.out.println("Successfully executed the task ...");
  54. System.exit(0);
  55. }
  56. }