Jump to content
telele97

Recursividade

Recommended Posts

telele97

Preciso de criar uma função recursiva que faça o seguinte cálculo :

f(p, q) = pf(p − 2, q) + qf(p, q − 2)

com f(0,q)=0, f(p,0)=1 e f(0,0)=5 sendo que p e 1 nao podem ser negativos

comecei por fazer o seguinte código só que não consigo passar daqui :S

int f(int p, int q){
int soma=0;
if(p>=0 && q>=0){
if(p==0 && q!=0)
return 0;
else if(q==0 && p!=0)
return 1;
else if(q==0 && p==0)
return 5;
}else{
return -1;
}

return q*f(p-2,q);
}

Share this post


Link to post
Share on other sites
KTachyon

A função só é recursiva se se chamar a si própria. No teu caso, a própria função nunca chega a ser chamada:

int f(int p, int q) {
   int soma=0;

   if(p >= 0 && q >= 0) {
       if(p == 0 && q != 0)
           return 0;
       else if(q == 0 && p!=0)
           return 1;
       else if(q == 0 && p == 0)
           return 5;
   }
   else {
       return -1;
   }

   return q*f(p-2,q);
}

EDIT: Pois, faltou-me o caso em que os dois são diferentes de zero e a função passa. Tens que retornar o resultado das chamadas, ou seja

return q*f(p-2, q) + p*f(p, q-2);

Edited by KTachyon

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.