Jump to content

Recommended Posts

Posted

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);
}
Posted (edited)

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • 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.