I am trying to create a bear game where the user enters a number (n), and the program will see if it can reach the number 42 by doing some specified steps. If it can't, then it notifies the user that number can't reach the goal.
These are the rules:
- If n is even, then you may give back exactly n/2 bears.
- If n is divisible by 3 or 4, then you may multiply the last two digits of n and give back this many bears.
- If n is divisible by 5, then you may give back exactly 42 bears.
Here's an example:
- 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!
Here's what I have so far:
#include <iostream>
using namespace std;
bool bears(int n);
int main(){
int number;
do{
cout<<"enter the amount of bears (press 0 to stop the program): ";
cin>>number;
if (bears(number)){
cout<<"you have reached the goal!"<<endl;
}
else{
cout<<"sorry, you have not reached the goal."<<endl;
}
}while(number != 0);
}
bool bears(int n){
if (n < 42){
return false;
}
else if (n == 42){
return true;
}
else{
if (n % 5 == 0){
return bears(n - 42);
}
else if(n % 2 == 0){
return bears(n / 2);
}
else if(n % 4 == 0|| n % 3 == 0)
{
int one;
int two;
one=n%10;
two=(n%100)/10;
return bears(n - one * two);
}
}
}
My program has the basic rules, but when I type in 250 bears it says it can't reach the goal. I understand what's happening in the code and why it can't reach the specified goal, but how do I make it universal so it'll work not just for the number 250, but for other numbers like: 84.