Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Beginner - Mistake on a simple code

Tags:

java

is my first time here so i dont know exactly how it works, so sorry for the mistakes.

What's the result from this function, when we give as "aktueller Parameter" the number 3?

(The original text:

Welches Ergebnis liefert diese Methode, wenn bei einem Aufruf als aktueller Parameter der Wert 3 übergeben wird?

Im studying in German, so i dont really know the english terms :/ )

public int m(int p)
{
   int result;
   if (p == 0)
   {
    result = 0;
   }
   else
   {
    result = 3*p + m(p-1);
   }
    return result;
   }

I have already tried it and the answer is 18, but when im trying to do it without any program the answer i find is 15:

result = 3 * 3 + 3(3-1);

Can someone please explain me why is 18 and not 15? Im assuming that i am making something wrong.

Thank you in advance.

like image 360
syiannop Avatar asked Sep 29 '26 07:09

syiannop


2 Answers

Let's break down this recursive call:

With m(3), p isn't 0, so we return 3*3 + m(2);.

3*3 + (m(2))

With m(2), p isn't 0, so we return 3*2 + m(1);.

3*3 + (3*2 + m(1))

With m(1), p isn't 0, so we return 3*1 + m(0);.

3*3 + (3*2 + (3*1 + m(0))

With m(0), p is 0, so we return 0. Then the recursive call stack unwinds.

3*3 + (3*2 + (3*1 + (0)) =
9 + (6 + (3 + 0)) = 
9 + (6 + 3) = 
9 + 9 = 
18
like image 186
rgettman Avatar answered Sep 30 '26 20:09

rgettman


When you see m(p-1), that means that you're calling the function m again from inside itself, which is called recursion.

Essentially, the arithmetic it's doing is 3*3+3*2+3*1 = 18.

like image 36
Embattled Swag Avatar answered Sep 30 '26 22:09

Embattled Swag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!