waltermilner

Untitled

Apr 23rd, 2018
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.67 KB | None | 0 0
  1. public class Test {
  2.  
  3.   static int steps(int n) {
  4.     if (n == 1) { // base case
  5.       return 0;
  6.     }
  7.     int opt1 = Integer.MAX_VALUE; // default values
  8.     int opt2 = Integer.MAX_VALUE;
  9.     int opt3 = Integer.MAX_VALUE;
  10.     // find the 3 options if possible
  11.     if (n % 3 == 0) {
  12.       opt1 = 1 + steps(n / 3);
  13.     }
  14.     if (n % 2 == 0) {
  15.       opt2 = 1 + steps(n / 2);
  16.     }
  17.     opt3 = 1 + steps(n - 1);
  18. // find minimum
  19.     opt2 = opt2 < opt1 ? opt2 : opt1;
  20.     opt3 = opt3 < opt2 ? opt3 : opt2;
  21.     return opt3;
  22.  
  23.   }
  24.  
  25.   public static void main(String[] args) {
  26.     for (int n = 1; n < 11; n++) {
  27.       System.out.println(n + " " + steps(n));
  28.     }
  29.   }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment