Somple Recursion Question

J

Johnny Shih

Hi guys,

I am having to figure out the recusion in this function.

int recfn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return recfn(v/2)+2;
else
return recfn(v-1)+3;
}


recfn(7) gives me 11
I am not able to figure out the steps and numbers that got added up to that.

Please help.

Thanks alot,
Johnny
 
C

Charles Harrison Caudill

Johnny Shih said:
I am having to figure out the recusion in this function.
int recfn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return recfn(v/2)+2;
else
return recfn(v-1)+3;
}

recfn(7) gives me 11
I am not able to figure out the steps and numbers that got added up to that.
Please help.
Thanks alot,
Johnny


recfn(7) -> 3 + recfn(6)
recfn(6) -> 2 + recfn(3)
recfn(3) -> 3 + recfn(2)
recfn(2) -> 2 + recfn(1)
recfn(1) -> 1

do the math
 
M

Martin Ambuhl

Johnny said:
Hi guys,

I am having to figure out the recusion in this function.

int recfn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return recfn(v/2)+2;
else
return recfn(v-1)+3;
}


recfn(7) gives me 11
I am not able to figure out the steps and numbers that got added up to
that.

recfn(7) = recfn(6) + 3
= recfn(3) + 2 + 3 = recfn(3) + 5
= recfn(2) + 3 + 5 = recfn(2) + 8
= recfn(1) + 2 + 8 = recfn(1) + 10
= 1 + 10 = 11

Now try doing your trivial busywork for yourself
 
J

James Hu

Hi guys,

I am having to figure out the recusion in this function.

int recfn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return recfn(v/2)+2;
else
return recfn(v-1)+3;
}


recfn(7) gives me 11
I am not able to figure out the steps and numbers that got added up to that.

Please help.

Try putting in printf statements.

int recfn(int v)
{
int r;

if(v==1 || v==0) {
r = 1;
} else if(v%2==0) {
r = recfn(v/2)+2;
} else {
r = recfn(v-1)+3;
}

printf("recfn(%d) == %d\n", v, r);
return r;
}

-- James
 
O

osmium

Johnny said:
I am having to figure out the recusion in this function.

int recfn(int v)
{
if(v==1 || v==0)
return 1;
if(v%2==0)
return recfn(v/2)+2;
else
return recfn(v-1)+3;
}


recfn(7) gives me 11
I am not able to figure out the steps and numbers that got added up to
that.

I think the most informative way to proceed is to add a print statement as
the first statement in the function. Print the value of v. If necessary,
keep adding print statements until it makes sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top