ADS: Addition und Multiplikation rekursiv

Diese Seite verwendet Cookies. Durch die Nutzung unserer Seite erklären Sie sich damit einverstanden, dass wir Cookies setzen. Weitere Informationen

  • ADS: Addition und Multiplikation rekursiv

    hier meine Lösung für die "Rekursive" mult-Methode:

    Quellcode

    1. public class RecurseMult {
    2. /**
    3. * @param args Kommandozeilenparameter
    4. */
    5. public static void main(String[] args) {
    6. test(142,369);
    7. }
    8. /**
    9. * testet, ob mult funktioniert
    10. * @param x Zahl1
    11. * @param y Zahl2
    12. */
    13. static void test(int x, int y){
    14. int res=mult(x,y);
    15. System.out.print(x + "," + y);
    16. if(x*y==res) System.out.println(" ok");
    17. else System.out.println(" falsch");
    18. }
    19. /**
    20. * Erhoeht eine Zahl um 1
    21. * @param x Zahl
    22. * @return x+1
    23. */
    24. static int inc(int x){
    25. return x+1;
    26. }
    27. /**
    28. * Verringert eine Zahl um 1
    29. * @param x Zahl
    30. * @return x-1
    31. */
    32. static int dec(int x){
    33. return x-1;
    34. }
    35. /**
    36. * Vorzeichenwechsel einer Zahl
    37. * @param x Zahl
    38. * @return x*(-1)
    39. */
    40. static int pm(int x){
    41. if(x==0)
    42. return 0;
    43. if(x<0)
    44. return inc(pm(inc(x)));
    45. else
    46. return dec(pm(dec(x)));
    47. }
    48. /**
    49. * Addition zweier Zahlen rekursiv
    50. * @param x Zahl1
    51. * @param y Zahl2
    52. * @return x+y
    53. */
    54. static int add(int x, int y){
    55. if( x==0 ) //x = 0
    56. return y;
    57. if( y==0 ) //y = 0
    58. return x;
    59. if( y>=1 && x>=1 ) //beide positiv
    60. return add(dec(x),inc(y));
    61. if( y>=1 && x<=1 ) //x negativ
    62. return add(dec(y),inc(x));
    63. if( y<=1 && x>=1 ) //y negativ
    64. return add(dec(x), inc(y));
    65. else //beide negativ
    66. return add(dec(x), inc(y));
    67. }
    68. /**
    69. * Multiplikation zweier Zahlen rekursiv
    70. * @param x Zahl1
    71. * @param y Zahl2
    72. * @return x*y
    73. */
    74. static int mult(int x, int y){
    75. if( x==0 || y==0 ) //x oder y = 0
    76. return 0;
    77. if(x==1) //x = 1
    78. return y;
    79. if(y==1) //y = 1
    80. return x;
    81. if(x>1)
    82. return add(y,mult(dec(x),y));
    83. else//(x<-1)
    84. return mult(pm(x),pm(y));
    85. }
    86. }
    Alles anzeigen