PPractick

DSA interview question

Prime Factorisation for Many Queries (Smallest Prime Factor Sieve)

Hard · Algorithms · Topics: math, number theory

The problem

A number-theory API receives hundreds of thousands of requests, each asking for the full prime factorisation of a number up to 10⁶ (for example 60 → 2 2 3 5). Trial division per request costs O(√n) each time. Precompute, once, the smallest prime factor (SPF) of every number with a sieve. Then factorising n is just repeatedly dividing by spf[n], which takes O(log n) steps, since each division at least halves n.

Example: 60 → 2 2 3 5; 97 → 97.

Function signature

vector<int> buildSpf(int maxN);                        // spf[x] = smallest prime factor of x
vector<int> factorize(int n, const vector<int>& spf);  // primes with multiplicity, ascending

Test cases

InputOutputExplanation
122 2 3
602 2 3 5
9797Prime: spf[97] = 97
1(none)
10242 2 2 2 2 2 2 2 2 22¹⁰
9999993 3 3 7 11 13 37

(Confirm: 1 ≤ n ≤ maxN (about 10⁶); factors are listed with multiplicity, in non-decreasing order.)

How interviewers phrase it

Clarifying questions to ask

  1. With multiplicity (2 2 3) or distinct primes (2 3)?
  2. What's the maximum value and the number of queries? (That decides between a sieve and trial division.)
  3. What output format? (Ascending factors.)

Follow-ups to expect

  1. "How is the SPF array built?"
  2. "Why is each query O(log n)?"
  3. "Why check spf[m] == m before writing?"
  4. "Can SPF be computed in linear time?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in