bigIntegerFakultaet.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import javax.swing.JOptionPane;
  2. import java.util.Arrays;
  3. import flanagan.io.Db;
  4. import java.math.BigInteger;
  5. /**
  6. * Das Program liest eine ganze Zahl N (0 <= N <= 20) und
  7. * berechnet den Wert von N! = 1 * 2 * ... * (N - 1) * N, wobei
  8. * 0! = 1 (nach Definition)
  9. */
  10. public class bigIntegerFakultaet
  11. {
  12. public static void main(String [] args)
  13. {
  14. int N = 0;
  15. /* Bedeutung:
  16. * N = die gesuchte Fakultaet
  17. * n = laufende Fakultaet-Zahl
  18. * resn = leufende Fakultaet: resn = (n - 1)!, n = 0, 1, 2, ... N
  19. * res = Resultat: res = n! = n*(n - 1)!, n = 0, 1, 2, ... N
  20. * = n* resn
  21. */
  22. boolean valid = false;
  23. try {
  24. N = Db.readInt("Gib die Grundzahl als eine Integer-Zahl ein und " +
  25. "bestätige mit ENTER ");
  26. } catch (NumberFormatException e) {
  27. System.exit(1);
  28. }
  29. // validate that: N >= 0
  30. if ( N < 0 ) {
  31. Db.show(
  32. "Falsche Eingabe: der Input-Parameter N < 0 \n"+
  33. "Probieren Sie nochmals! Das Programm ist sofort beendet!");
  34. System.exit(1);
  35. }
  36. // validation prompt
  37. Db.show(
  38. "Die Eingabe ist OK! Sie möchten also " + N + "! berechnen!");
  39. // special case: 0! = 1
  40. if (N == 0) {
  41. System.out.println("Fakultaet " + N + "! = " + 1);
  42. System.exit( 0 );
  43. }
  44. System.out.format("\n%s \t n! \n-------------------------------------", " n", N);
  45. // use big integer
  46. BigInteger bigN = BigInteger.valueOf(N);
  47. bigN.add(BigInteger.ONE);
  48. bigN = bigN.add(BigInteger.ONE);
  49. System.out.println(bigN);
  50. BigInteger res = BigInteger.valueOf(1);
  51. BigInteger resn = BigInteger.valueOf(1);
  52. for (BigInteger n = BigInteger.valueOf(1); n.compareTo(bigN) < 0; n = n.add(BigInteger.ONE))
  53. {
  54. res = n.multiply(resn); // current result
  55. resn = res; // new overall result
  56. System.out.format("\n %2d \t %-20d", n, res);
  57. }
  58. System.out.format("\n-------------------------------------");
  59. // solution prompt
  60. JOptionPane.showMessageDialog (null,
  61. N + "! = " + res,
  62. "Lösung", JOptionPane.INFORMATION_MESSAGE);
  63. }
  64. }