Prime factorisation of a Number
Pattern: Prime factorisation
For many queries, sieve the smallest prime factor of every number up to the largest query. Then factorise each query by repeatedly dividing by its smallest prime factor, recording each one.
The problem
Given an array of queries, return for each one its prime factors in increasing order, with repeats (12 gives [2, 2, 3]; 1 gives []).
Think first
- Why is trial division per query slow for many queries?
- What does a smallest-prime-factor table store?
- How many divisions does one query need?
Hints
Brute force, and why it fails
Trial division for each query: O(q √max).
The key insight
One sieve shared by all queries makes each factorisation logarithmic.
Dry run
Queries [2, 3, 4, 5, 6]. spf: 2→2, 3→3, 4→2, 5→5, 6→2.
Step 1 of 2
The plan
spf = smallest prime factor sieve up to max(queries)
for q: while q > 1: record spf[q]; q = q / spf[q]
Complexity
- Time
O(max log log max + total factors)- Space
O(max)
The sieve dominates.
Edge cases
- 1: no factors.
- A prime: itself.
- Powers of 2.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> primeFactors(int[] queries) {
int max = 2;
for (int q : queries) max = Math.max(max, q);
int[] spf = new int[max + 1]; // spf[x]: the smallest prime factor of x
for (int i = 2; i <= max; i++) {
if (spf[i] != 0) continue;
for (int j = i; j <= max; j += i) if (spf[j] == 0) spf[j] = i; // i is prime: it is the smallest factor of its unmarked multiples
}
List<List<Integer>> out = new ArrayList<>();
for (int q : queries) {
List<Integer> f = new ArrayList<>();
for (int x = q; x > 1; x /= spf[x]) f.add(spf[x]); // peel off the smallest factor each time
out.add(f);
}
return out;
}
}C++
class Solution {
public:
vector<vector<int>> primeFactors(vector<int>& queries) {
int mx = 2;
for (int q : queries) mx = max(mx, q);
vector<int> spf(mx + 1, 0); // spf[x]: the smallest prime factor of x
for (int i = 2; i <= mx; i++) {
if (spf[i] != 0) continue;
for (int j = i; j <= mx; j += i) if (spf[j] == 0) spf[j] = i; // i is prime: smallest factor of its unmarked multiples
}
vector<vector<int>> out;
for (int q : queries) {
vector<int> f;
for (int x = q; x > 1; x /= spf[x]) f.push_back(spf[x]); // peel off the smallest factor each time
out.push_back(f);
}
return out;
}
};Python
class Solution:
def primeFactors(self, queries: list[int]) -> list[list[int]]:
mx = max(queries + [2])
spf = [0] * (mx + 1) # spf[x]: the smallest prime factor of x
for i in range(2, mx + 1):
if spf[i] == 0:
for j in range(i, mx + 1, i): # i is prime: smallest factor of its unmarked multiples
if spf[j] == 0:
spf[j] = i
out = []
for q in queries:
f, x = [], q
while x > 1: # peel off the smallest factor each time
f.append(spf[x])
x //= spf[x]
out.append(f)
return outCommon mistakes
- Missing repeated factors.
- Treating 1 as prime.