Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive method to meet this specification: public static boolean bears

ID: 3768812 • Letter: W

Question

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).

Explanation / Answer

public static boolean bears(int n) { int ones, tens; if (n < 42) return false; if (n == 42) return true; if ((n%2) == 0) if (bears(n/2)) return true; if (((n%3)==0) || ((n%4)==0)) { % 10; tens = (n % 100)/10; if ((ones != 0) && (tens != 0) && (bears(n-ones*tens))) return true; } if ((n%5) == 0) if (bears(n-42)) return true; return false; }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote