Code:
class Faktorijel
{
// Ovo je rekurzivna metoda.
int fakt(int n)
{
System.out.println("Method: "+n);
if(n == 1)
{
System.out.println("Returned: "+n);
return 1;
}
else
{
int result = n* fakt(n-1);
System.out.println("Result: "+result+" fakt("+n+"-1)");
return result;
}
}
}
public class Rekurzija
{
public static void main(String[] args)
{
Faktorijel f = new Faktorijel();
System.out.println("Faktorijel broja 5 je: "+f.fakt(5));
}
}
class Faktorijel
{
// Ovo je rekurzivna metoda.
int fakt(int n)
{
System.out.println("Method: "+n);
if(n == 1)
{
System.out.println("Returned: "+n);
return 1;
}
else
{
int result = n* fakt(n-1);
System.out.println("Result: "+result+" fakt("+n+"-1)");
return result;
}
}
}
public class Rekurzija
{
public static void main(String[] args)
{
Faktorijel f = new Faktorijel();
System.out.println("Faktorijel broja 5 je: "+f.fakt(5));
}
}
Output:
Method: 5
Method: 4
Method: 3
Method: 2
Method: 1
Returned: 1
Result: 2 fakt(2-1)
Result: 6 fakt(3-1)
Result: 24 fakt(4-1)
Result: 120 fakt(5-1)
Faktorijel broja 5 je: 120
1.
Malo me buni ova lokalna promenljiva result. Evo kako sam je ja razumeo
Kada se dodje do ovog dela:
int result = n* fakt(n-1);
Promenljiva result dobija vrednost :
int result = 5 * fakt(5 - 1) => 4* fakt(4 - 1) => 3* fakt(3 - 1) => 2 * fakt(2 - 1);
2 * fakt(2-1) = 2 * 1 = 2
3 * fakt(3-1) = 3 * 2 = 6 // Kada se ovo racuna fakt(3-1) > fakt(2-1)
4 * fakt(4-1) = 4 * 6 = 24 // Kada se ovo racuna fakt(4-1) > fakt(3-1) > fakt(2-1)
5 * fakt(5-1) = 5 * 24 = 120 // Kada se ovo racuna fakt(5-1) > fakt(4-1) > fakt(3-1) > fakt(2-1)
Sto se veci broj n to se sve vrti ova metoda dublje i dublje ?