Imagine a game where you\'re given a starting number and can repeatedly make one
ID: 3874936 • Letter: I
Question
Imagine a game where you're given a starting number and can repeatedly make one of two moves.
* You can either divide the number by three if it's divisible by three, or subtract seven.
* You win the game if you can reduce the number to 1.
* For example, you can win with 15 because you can subtract 7 twice
* (you would also be allowed to divide 15 by 3, but that doesn't work for 15)
* You can win with 3 because you can divide by 3. You can win with 10 because you can
* subtract 7 and divide it by 3.
* You can't win with 5 or 6
* Write a function that returns if the game can be won with a particular starting number.
* @param startingNumber
* @return true if you can win the numbers game, false otherwise
Explanation / Answer
The programming language is not specified. Assuming it is in java. Let me know if you wanted it in C/C++.
The following function implements the functionality specified in the question. To demonstrate that the function is correct, I have implemented a small main program including the function. That NumberGame class is for testing only. You only need the function canWin(). Hope it was helpful.
public static boolean canWin(int startingNumber)
{
if(startingNumber == 1)
return true;
if(startingNumber < 1)
return false;
if(startingNumber % 3 == 0 && canWin(startingNumber/3))
return true;
else
return canWin(startingNumber - 7);
}
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
==============================================
FULL TESTING PROGRAM
=======================================
File: NumberGame.java
import java.util.Scanner;
public class NumberGame {
public static boolean canWin(int startingNumber)
{
if(startingNumber == 1)
return true;
if(startingNumber < 1)
return false;
if(startingNumber % 3 == 0 && canWin(startingNumber/3))
return true;
else
return canWin(startingNumber - 7);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a starting number: ");
int n = keyboard.nextInt();
if(canWin(n))
System.out.println("You can win with " + n);
else
System.out.println("You can not win with " + n);
}
}
output
=====
Enter a starting number: 3
You can win with 3
--------
Enter a starting number: 15
You can win with 15
-------
Enter a starting number: 5
You can not win with 5
--------
Enter a starting number: 6
You can not win with 6