hier meine Lösung für die "Rekursive" mult-Methode:
Alles anzeigen
Quellcode
- public class RecurseMult {
- /**
- * @param args Kommandozeilenparameter
- */
- public static void main(String[] args) {
- test(142,369);
- }
- /**
- * testet, ob mult funktioniert
- * @param x Zahl1
- * @param y Zahl2
- */
- static void test(int x, int y){
- int res=mult(x,y);
- System.out.print(x + "," + y);
- if(x*y==res) System.out.println(" ok");
- else System.out.println(" falsch");
- }
- /**
- * Erhoeht eine Zahl um 1
- * @param x Zahl
- * @return x+1
- */
- static int inc(int x){
- return x+1;
- }
- /**
- * Verringert eine Zahl um 1
- * @param x Zahl
- * @return x-1
- */
- static int dec(int x){
- return x-1;
- }
- /**
- * Vorzeichenwechsel einer Zahl
- * @param x Zahl
- * @return x*(-1)
- */
- static int pm(int x){
- if(x==0)
- return 0;
- if(x<0)
- return inc(pm(inc(x)));
- else
- return dec(pm(dec(x)));
- }
- /**
- * Addition zweier Zahlen rekursiv
- * @param x Zahl1
- * @param y Zahl2
- * @return x+y
- */
- static int add(int x, int y){
- if( x==0 ) //x = 0
- return y;
- if( y==0 ) //y = 0
- return x;
- if( y>=1 && x>=1 ) //beide positiv
- return add(dec(x),inc(y));
- if( y>=1 && x<=1 ) //x negativ
- return add(dec(y),inc(x));
- if( y<=1 && x>=1 ) //y negativ
- return add(dec(x), inc(y));
- else //beide negativ
- return add(dec(x), inc(y));
- }
- /**
- * Multiplikation zweier Zahlen rekursiv
- * @param x Zahl1
- * @param y Zahl2
- * @return x*y
- */
- static int mult(int x, int y){
- if( x==0 || y==0 ) //x oder y = 0
- return 0;
- if(x==1) //x = 1
- return y;
- if(y==1) //y = 1
- return x;
- if(x>1)
- return add(y,mult(dec(x),y));
- else//(x<-1)
- return mult(pm(x),pm(y));
- }
- }