PPractick

DSA interview question

All Divisors of a Number

Easy · Algorithms · Topics: math, number theory

The problem

A party-planning app splits n guests into equal-sized tables and wants to show every possible table size, meaning all divisors of n in increasing order. Checking every number up to n is O(n), too slow for n near 10⁹. Divisors come in pairs (i, n / i) with i ≤ √n, so scanning i up to √n finds them all. Collect the small halves in order and the large halves in reverse, and take care not to list √n twice for perfect squares.

Example: 20 → 1 2 4 5 10 20.

Function signature

vector<long long> divisors(long long n);  // ascending; n >= 1

Test cases

InputOutputExplanation
201 2 4 5 10 20Pairs (1, 20), (2, 10), (4, 5)
211911 21191A prime
361 2 3 4 6 9 12 18 366 · 6 is listed once
11
121 2 3 4 6 12

(Confirm: n ≥ 1; each divisor appears once, in increasing order.)

How interviewers phrase it

Clarifying questions to ask

  1. Should 1 and n be included? (Yes.)
  2. Must the output be sorted?
  3. How large is n? (Up to about 10⁹, which means O(√n).)

Follow-ups to expect

  1. "Why stop at √n?"
  2. "How do you keep the output sorted without sorting?"
  3. "Perfect squares?"
  4. "How many divisors can a number have?"
  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