bigIntegerPotenzen.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 bigIntegerPotenzen
  11. {
  12. public static void main(String [] args)
  13. {
  14. int N = 0;
  15. int B = 3;
  16. /* Bedeutung:
  17. * N = die gesuchte Fakultaet
  18. * n = laufende Fakultaet-Zahl
  19. * resn = leufende Fakultaet: resn = (n - 1)!, n = 0, 1, 2, ... N
  20. * res = Resultat: res = n! = n*(n - 1)!, n = 0, 1, 2, ... N
  21. * = n* resn
  22. */
  23. // get Basiszahl input
  24. try {
  25. B = Db.readInt("Basiszahl:" +
  26. "bestätige mit ENTER ");
  27. } catch (NumberFormatException e) {
  28. System.exit(1);
  29. }
  30. // get Exponent input
  31. try {
  32. N = Db.readInt("Exponent:" +
  33. "bestätige mit ENTER ");
  34. } catch (NumberFormatException e) {
  35. System.exit(1);
  36. }
  37. // validate that: N, B >= 0
  38. if ( B < 0) {
  39. Db.show(
  40. "Falsche Eingabe: der Input-Parameter N < 0 \n"+
  41. "Probieren Sie nochmals! Das Programm ist sofort beendet!");
  42. System.exit(1);
  43. }
  44. // use big integer
  45. BigInteger bigN = BigInteger.valueOf(N);
  46. BigInteger bigB = BigInteger.valueOf(B);
  47. bigN.add(BigInteger.ONE);
  48. bigN = bigN.add(BigInteger.ONE);
  49. BigInteger res = BigInteger.valueOf(1);
  50. BigInteger resn = BigInteger.valueOf(1);
  51. //for (BigInteger n = BigInteger.valueOf(1); n.compareTo(bigN) < 0; n = n.add(BigInteger.ONE))
  52. if (N < 0) {
  53. //res = BigInteger.valueOf(1337);
  54. res = BigInteger.ONE.divide(BigInteger.valueOf(2));
  55. double negativeResult = res.doubleValue();
  56. JOptionPane.showMessageDialog (null,
  57. B + "^" + N + " = " + negativeResult,
  58. "Lösung", JOptionPane.INFORMATION_MESSAGE);
  59. } else {
  60. res = bigB.pow(N);
  61. resn = res;
  62. JOptionPane.showMessageDialog (null,
  63. B + "^" + N + " = " + res,
  64. "Lösung", JOptionPane.INFORMATION_MESSAGE);
  65. }
  66. // solution prompt
  67. }
  68. }