Simple recursion question

I have a small recursive function I am trying to follow, but I'm just not getting it. I know if I put in the number 36, it returns 5. I did some calculations on paper, but I am obviously missing something because my answer doesn't match the function answer. Any help, tips, or suggestions are greatly appreciated!

1
2
3
4
5
6
7
8
9
F(36);

unsigned F(unsigned n)
{
    if(n < 2)
        return 0;

    return 1 + F(n / 2);
}


5 seems about right to me.

The calls:
36 - is 36 < 2 no... F(18)
18 - is 18 < 2 no... F(9)
9 - is 9 < 2 no... F(4) (int division)
4 - is 4 < 2 no... F(2)
2 - is 2 < 2 no... F(1)
1 - is 1 < 2 yes...

return 0 to F(2)
return 1 to F(4)
return 2 to F(9)
return 3 to F(18)
return 4 to F(36)
return 5 to main()

5 is also the correct answer, as 2^5 <= 36 < 2^6
Last edited on
Thanks! I think I've got it now.
Topic archived. No new replies allowed.