Advertisement
Guest User

Untitled

a guest
Dec 11th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1.  
  2. class Solution {
  3.    
  4.     // O(sqrt(n)) (constrained by prime factorization)
  5.     //
  6.     // We use the four-square theorem to notice that the result is always at most 4.
  7.     // We can then check whether n is a square to find out whether the result is 1, if not we can use two-square and
  8.     // three-square theorems to find out whether the result is 2 or 3, else it's 4.
  9.     //
  10.     // If someone finds a way to check whether n is a sum of two squares efficiently, we can reduce the complexity
  11.     // to O(log n)! (Same if the prime factorization is known)
  12.    
  13.    
  14.     public static int numSquares(int n) {
  15.         if (n == 0) return 0;
  16.         if (n == (int) Math.pow(Math.round(Math.sqrt(n)), 2)) return 1;
  17.  
  18.         Map<Integer, Integer> primeFactors = findPrimeFactors(n);
  19.         if (primeFactors.entrySet().stream().filter(e -> e.getKey() % 4 == 3).allMatch(e -> e.getValue() % 2 == 0)) return 2;
  20.         if (primeFactors.getOrDefault(2, 0) % 2 == 0 && (n >>> Integer.numberOfTrailingZeros(n)) % 8 == 7) return 4;
  21.         return 3;
  22.     }
  23.    
  24.    
  25.    
  26.    
  27.    
  28.     public static Map<Integer, Integer> findPrimeFactors(int n) {
  29.         Map<Integer, Integer> res = new HashMap<>();
  30.         for (int i = 2; i*i <= n; i++) {
  31.             while (n % i == 0) {
  32.                 res.merge(i, 1, Integer::sum);
  33.                 n /= i;
  34.             }
  35.         }
  36.         if (n > 1) res.merge(n, 1, Integer::sum);
  37.         return res;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement