Recursive Boolean Function

Hello,
I am writing a program for an exercise homework and for some reason my Boolean function is not doing any of the calculations.

This was the question: At McDonald's, you can purchase 6, 9 and 20 packs of McNuggets. Call a number of McNuggets buyable if it is possible to buy that number of McNuggets. Write a recursive boolean method called
buyable(int n) that returns true if n is buyable.
e.g. buyable(15) is true, buyable(11) is false.

ret is always equal to zero, I am not sure how to make it work.

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

using namespace std;

bool buyable(int n) // calculate the sum of n+(n-1)+(n-2) + … + 2+1
{
  bool ret = false;
    if (n<1)
    {
    return false;
    }

    if((n%6)==0 || (n%9)==0 ||(n%20)==0)
     {
         return true;
            cout<<"n: "<<n;
     }
if (ret == false && n > 20 || n > 9 || n > 6)
{
    ret = buyable(n - 20);
    cout<<"n: "<<n<<endl;
    cout<<"ret: "<<ret;
}


return ret;


}

int main()
{

    //cout<<"Enter the number of McNuggets you would like to purchase. ";
buyable(15);
    if (buyable(11)==true)
    {
        cout<<"You can buy "<<buyable(11)<<" McNuggets!"<<endl;
    }
 if (buyable(11)==false)
    {
        cout<<"You can not buy "<<"n"<<" McNuggets!"<<endl;
    }
    //cout<<buyable(15);

    return 0;
}



Thanks
Enes
Line 18: The && operator has higher priority than ||, thus the expression is evaluated as:
 
if ( (ret == false && n > 20) || n > 9 || n > 6)

Probably not what you wanted.
I suspect you wanted:
 
if (ret == false && (n > 20 || n > 9 || n > 6))  // Note the parens 

However, ret==false is irrelevant. It is initialized to false and not changed between lines 7 and 18, therefore there is no need to test that it is false.

Line 16 will never get executed.

1
2
3
4
5
6
bool buyable( int n )
{
    if( n < 6 ) return false ;
    else if( n==6 || n==9 || n==20 ) return true ;
    else return buyable(n-6) || buyable(n-9) || buyable(n-20) ;
}

http://coliru.stacked-crooked.com/a/c221dd27b7652c9f
Thank you JLBorges it worked! Thanks for everyones help!
Topic archived. No new replies allowed.