Auf Thema antworten

Hallo zusammen,


folgendes Programm (Uni-Hausaufgabe) habe ich bekommen:


[code=Java]

public class Binom {


    static int callstobinom = 0; // count how often function binom is called

       

    private static long binom(int m, int k) {

        callstobinom++;

               

        k = Math.min(k, m-k);

        if (k == 0){

            return 1;

        } else{

            return binom(m-1,k-1)+ binom(m-1,k);

        } 

       

    }


    public static void main(String[] args) {

        int m = Integer.parseInt(args[0]);

        System.out.printf("%21d = %s%n",  Long.MAX_VALUE, "Long.MAX_VALUE");

        System.out.printf("%21d = %s%n",  m,              "m");

       

        for (int k = 0;   k <= m;   ++k) {

            callstobinom = 0; // Reset counter

            System.out.printf("%21d = (%2d aus %2d) [binom was called %3d times] %n", binom(m,k), k, m, callstobinom);

        }

    }

}


[/code]


Zur Vereinfachung soll ich einen Wert, der bereits einmal berechnet wurde in einem zweidimensionalen Array abspeichern und bei Bedarf wieder laden, damit es schneller geht. Das habe ich nach stundenlangem Ausprobieren herausbekommen:


[code=Java]

public class Binom {


     static int callstobinom = 0; // count how often function binom is called

     long datacatcher[][];

     static long h = 0;


     private static long binom(int m, int k) {

         callstobinom++;

         k = Math.min(k, m-k);

         if (k == 0){

             return 1;

         } else{


             return binom(m-1,k-1)+ binom(m-1,k);

         }


     }


     public static void main(String[] args) {

         int m = Integer.parseInt(args[0]);

         System.out.printf("%21d = %s%n",  Long.MAX_VALUE, "Long.MAX_VALUE");

         System.out.printf("%21d = %s%n",  m,              "m");

         for (int k = 0;   k <= m;   ++k) {

             callstobinom = 0; // Reset counter

             long datacatcher[][]= new long[k+1][m+1];

             h = binom(m,k);

             datacatcher[k][m]=h;

             System.out.printf("%21d = (%2d aus %2d) [binom was called %3d ti    mes] %n", h, k, m, callstobinom);

         }

 }

}

[/code]


Das Speichern funktioniert damit mit der Hilfsvariable h, aber wie kann ich einen Wert wieder "laden" und dann damit weiterrechnen?


Vielen Dank für die Hilfe!


Liebe Grüße


Chris



Oben