0
$\begingroup$

The question was to convert this recursive code with intermediate variables to a functional program code without any intermediate variables.

product(p,q){
     r=0
     if(q==1)
       return r
     else{
        if(q%2!=0){
          r=r+p
          q--
          product(p,q)
        }
        else{
          r=r+2p
          q=q/2
          product(p,q)
        }
     }
}

The code without intermediate variables that I wrote,

product(p,q){
     if(q==1)
       return r
     else{
        if(q%2!=0){ 
          product(p,q--)
          return r+p
        }
        else{
          product(p,q/2)
          return r+2p
        }
     }
}

Is this code correct?

For example if we take (5,3) it will output 15 as following if we use the first recursive code.

(p,q-1) --> (5,2)   as p=3 is odd       r=r+p=0+5=5

(p,q/2) --> (5,1)   as p=2 is even      r=r+2p=5+10=15

at this point it returns r which is equal to 15.

In the code without intermediate variables the return values are stored in the stack separately and they return r values separately. How can I add the r values without storing them in an intermediate variable?

(p,q-1) --> (5,2)   as p=3 is odd      return r+p=0+5=5

(p,q/2) --> (5,1)   as p=2 is even     return r+2p=0+10=10

I am new to learning recursion and I am really sorry if the question is not very clear.

$\endgroup$
5
  • $\begingroup$ The code wont compile in any language since you haven't defined what $r$ is $\endgroup$
    – nir shahar
    Jan 15 at 11:26
  • $\begingroup$ If I declare r=0 before the function starts will it be okay? @nirshahar $\endgroup$ Jan 15 at 12:08
  • $\begingroup$ Is the code correct? Run it on a few inputs and see if you get the same answer as the original code. $\endgroup$ Jan 15 at 12:13
  • $\begingroup$ @SanduniAaloka of course not, since you never modify $r$ - it will always be $0$. It will technically compile, but would it really result in the answer you want? $\endgroup$
    – nir shahar
    Jan 15 at 14:01
  • $\begingroup$ @nirshahar No it doesn't give the answer I want. It wouldn't even return 0 for r and I have no idea of how to add those two r values in the if-else condition. $\endgroup$ Jan 15 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.