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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
2. A Teddy Bear Picnic
This question involves a game with teddy bears. The game starts when I give you some bears. You can then give back some bears, but you must follow these rules (where n is the number of bears that you have):
1. If n is even, then you may give back exactly n/2 bears.
2. If n is divisible by 3 or 4, then you may multiply the last two digits of n and give back this many bears. (By the way, the last digit of n is n%10, and the next-to-last digit is ((n%100)/10).
3. If n is divisible by 5, then you may give back exactly 42 bears.
The goal of the game is to end up with EXACTLY 42 bears.
For example, suppose that you start with 250 bears. Then you could make these moves:
--Start with 250 bears.
--Since 250 is divisible by 5, you may return 42 of the bears, leaving you with 208 bears.
--Since 208 is even, you may return half of the bears, leaving you with 104 bears.
--Since 104 is even, you may return half of the bears, leaving you with 52 bears.
--Since 52 is divisible by 4, you may multiply the last two digits (resulting in 10) and return these 10 bears. This leaves you with 42 bears.
--You have reached the goal!
Write a recursive method to meet this specification:
public static boolean bears(int n)
// Postcondition: A true return value means that it is possible to win
// the bear game by starting with n bears. A false return value means that
// it is not possible to win the bear game by starting with n bears.
// Examples:
// bear(250) is true (as shown above)
// bear(42) is true
// bear(84) is true
// bear(53) is false
// bear(41) is false
Hint: To test whether n is even, use the expression ((n % 2) == 0).
#include <iostream>
using namespace std;
bool BearShare(int x)
{
if(x==42)
return true;
else if(x%5==0)
{
BearShare(42-x);
}
else if(x%4==0||x%3==0)
{
int one;
int two;
one=x%10;
two=(x%100)/10;
BearShare(one*two);
}
else if(x%2==0)
{
BearShare(x/2);
}
else
return false;
}
int main()
{
int x;
cin>>x;
BearShare(x);
if (BearShare(x)==true)
cout<<"you win"<<endl;
else
cout<<"keep trying"<<BearShare(x)<<endl;
system("pause");
return 0;
}
| |