Answered # Recursion

VernonDozier 2,218 Discussion Starter Gagless Featured Reply Lerner 582 OK, so HostGator for some reason no longer allows gcc/g++ access unless you have a Designated Server account, which is a lot of money to spend just to compile my "Hello World" program. Thus I figured I'd compile at home, then upload. Program is your regular old bare-bones Hello World ...

0

Having trouble understanding how this recursive function works.

`int F( int X ) { return (X<=0) ? 3 : F(X/2)+F(X-3); }`

I understand the first part, give it a value 0 or less, get back 3, fine. But greater values I don't understand 2 returns 9, 3 returns 9, 4 returns 15. How?

It's equivalent to this function. Not sure if that's what your question is.

```
int F( int X )
{
if (X <= 0)
return 3;
else
return F(X/2) + F(X-3);
}
```

0

I'm aware of how the trinary operator works, its what's going on in the function that has me stumped. After it checks the value to see if its lets than or equal to zero, what is it doing afterwards to return a value?

1

Given: x == 2 or F(2)

I'll rewrite it as

(F(1) + F(-1))

which I'll rewrite as

((F(0) + F(-2)) + 3)

which I'll rewrite as

((3 + 3) + 3)

which is 9

Given x == 3 or F(3)

OR

(F(1) + F(0))

OR

((F(0) + F(-2)) + 3)

OR

((3 + 3) + 3)

which is 9

You can work out x == 4 on your own. There are a few more nested () but it's not that hard to do.

This question has already been answered. Start a new discussion instead.

Recommended Articles

Hi. I have a form with list box : lst_product, datagridview : grd_order and button: btn_addline. lst_product has a list of product ids selected from database (MS Acess 2013) , grd_order is by default empty except for 2 headers and btn_addline adds rows to grd_order.

btn_addline :

`Private Sub btn_addline_Click(ByVal ...`

I don’t want at this stage work on a big separate project as I've already got plenty ...