Advertisement
ogv

Untitled

ogv
Aug 17th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. /*
  2. Runtime: 0 ms, faster than 100.00% of Java online submissions for Divisor Game.
  3. Memory Usage: 32.8 MB, less than 13.33% of Java online submissions for Divisor Game.
  4. */
  5. class Solution {
  6.     public boolean divisorGame(int N) {
  7.         if (N == 0) return true;
  8.        
  9.         byte[] cache = new byte[N + 1];
  10.         return wins(N, cache) == +1;
  11.     }
  12.    
  13.     private byte wins(int n, byte[] cache) {
  14.         if (n == 1) return -1;
  15.         if (cache[n] != 0) return cache[n];
  16.        
  17.         byte result = -1;
  18.         for (int x = 1; x * x <= n; x++ ) {
  19.             if (n % x == 0) {
  20.                 if (wins(n - x, cache) == -1) {
  21.                     result = +1;
  22.                     break;
  23.                 }
  24.                
  25.                 int y = n / x;
  26.                 if (y < n && wins(n - y, cache) == -1) {
  27.                     result = +1;
  28.                     break;
  29.                 }
  30.             }
  31.         }
  32.        
  33.         cache[n] = result;
  34.         return result;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement