CodeBarn
10/4/2018 - 2:35 AM

cpp template - Prime factorization

Prime factorization. O(log(n))

// Prime factorization, n >= 0
// Complexity: O(log(n))
vi factor(int n) {
  vi f;
  if (n < 2) return vi();  // vi(1, n), if want 'n' for n < 2
  while (~n & 1) n /= 2, f.push_back(2);
  for (ll p = 3; p * p <= n; p += 2)
    while (n % p == 0) n /= p, f.push_back((int)p);
  if (n > 1) f.push_back(n);
  return f;
}