Fakultät-Rechner in Java programmieren?
Ich habe folgendes Programm:
public class test {
public static void main(String[] args) {
System.out.println(fakulteat(5));
}
public static int fakulteat(int zahl) {
if (zahl == 1) {
return 1;
} else {
return zahl * fakulteat(zahl - 1);
}
}
}
Hier wird jetzt ja die Fakultät berechnet durch diese rekursive Methode.
Mein Problem steckt folgender Zeile:
return zahl * fakulteat(zahl - 1);
Damit gibt man dann so gesagt ” 5 * 4! ” an die Methode zurück.
Was ich mich aber Frage ist halt, wieso ” fakulteat(zahl – 1) ” jetzt eine Fakultät darstellt. Der Methode gibt sich selbst damit doch nur einen Wert zurück, woher weiß aber die Methode, dass dann z.B. 4! = 1 * 2 * 3 * 4 gemeint ist?
It just depends on the recursion. The method calls itself and breaks off when the number is = 1.
So you reckon 5*fak(4)
That’s 5*4*fak(3) etc. Until you arrive at 1.
Why not go
?
Because fak(6) would then output, for example, 6*5 = 30. It has to go down to 1:
6 = 5*4*3*2*1 = 720
Of course not. You return now 6*5
Okay, thanks, but is not 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720 ?
Because the fakulteat method is recursive and calls itself with a changed parameter. The recursion breaks when the method is called with the parameter 1, because the faculty of 1 is by definition 1.
Right. And strictly speaking, it would have to stop at 0.
Why?
if (number == 1) {
return 1;
}
is clear. At “1” do not call yourself, but return “1”.
Why not go
?
When you call the fakultaet(5), the return value is 5 * (5 – 1) = 5 * 4 = 20. This is clearly wrong.
I forgot the 0! However, this does not end in any continuous loop, because at some point an overflow takes place in the positven numbers and then ends at 1. The result will then probably depend on platform and compiler.
From calls like falkultaet(-1) I don’t start at all.
Either before the first call of the function fakultaet() checks whether the transferred values are sensible or in the function itself, which would greatly slow the effectiveness, because then the test takes place again and again.
Then it is still to check how large the numbers can be included. Here, the platform and compiler are also crucial, otherwise the return value runs over and nonsense comes as a return.
The program from the questioner is therefore far from a program that meets the requirement for the calculation of the faculty without errors.
If you really have a lot of memory, you can also install a value table beforehand, where only the value n! is drawn to a given n .
A really good-optimizing compiler could calculate that in the call
better just
must be in the function itself optimized.
MyTwoCents
0! = 1. That’s defined. It’s gonna be overlooked. A call with 0 as a parameter ends in an endless loop.