primeFactors function

List<int> primeFactors(
  1. int n
)

Prime factors (small numbers). Returns list of prime factors with multiplicity. Audited: 2026-06-12 11:26 EDT

Implementation

List<int> primeFactors(int n) {
  if (n <= 1) return <int>[];
  final List<int> out = <int>[];
  int x = n.abs();
  // Trial division: divide out each factor fully (the inner while) before moving
  // on, so factors are emitted with multiplicity and in ascending order. Once a
  // factor exceeds the running square root, any remainder above 1 is itself a
  // prime (it can have no smaller factor left) and is appended below.
  // The limit is cached and recomputed only when x shrinks, instead of taking a
  // square root on every iteration.
  int limit = isqrt(x);
  for (int d = 2; d <= limit; d++) {
    // Skip non-divisors early so the limit is left untouched for them.
    if (x % d != 0) continue;
    while (x % d == 0) {
      out.add(d);
      x ~/= d;
    }
    limit = isqrt(x);
  }
  if (x > 1) out.add(x);
  return out;
}