Find all divisors of a natural number
EasyUpdated: Sep 19, 2025
Problem
Given a natural number n, list all distinct positive divisors (factors) of n.
Input: a single integer n (assume n >= 1).
Output: all divisors of n (we will show multiple methods; one prints in arbitrary order, one prints sorted).
Examples
Example 1
Input: n = 10
Output: 1 2 5 10
Example 2
Input: n = 100
Output: 1 2 4 5 10 20 25 50 100
Example 3
Input: n = 125
Output: 1 5 25 125
Notes
- There is no exact single LeetCode problem that is simply "list all divisors of n", but related number-theory problems and divisor-queries are common.
Solution
We present three methods:
- Method 1 — Brute force check (O(n)).
- Method 2 — Check up to
sqrt(n)and output pairs (O(sqrt(n))). - Method 3 — Check up to
sqrt(n)and collect halves to print in sorted order (O(sqrt(n))).
Method 1 — Brute force
Intuition
Check every integer i from 1 to n and test whether i divides n.
Approach
- For
ifrom1ton:- If
n % i == 0, outputi.
- If
Edge cases: n == 1 returns 1.
Code
C++
class Solution {
public:
static void printDivisorsBrute(int n) {
for (int i = 1; i <= n; ++i) {
if (n % i == 0) std::printf("%d ", i);
}
}
};
Go
package main
import "fmt"
func PrintDivisorsBrute(n int) {
for i := 1; i <= n; i++ {
if n%i == 0 { fmt.Printf("%d ", i) }
}
}
Java
class Solution {
public static void printDivisorsBrute(int n) {
for (int i = 1; i <= n; ++i) if (n % i == 0) System.out.printf("%d ", i);
}
}
Kotlin
object Solution {
fun printDivisorsBrute(n: Int) {
for (i in 1..n) if (n % i == 0) print("$i ")
}
}
Python
class Solution:
def print_divisors_brute(self, n: int) -> None:
for i in range(1, n+1):
if n % i == 0:
print(i, end=' ')
Rust
pub struct Solution;
impl Solution {
pub fn print_divisors_brute(n: i64) {
for i in 1..=n { if n % i == 0 { print!("{} ", i); } }
}
}
Complexity
- ⏰ Time complexity:
O(n)— tests every integer up ton. - 🧺 Space complexity:
O(1).
Method 2 — Check up to sqrt(n) and output pairs
Intuition
Divisors come in pairs (i, n/i). If i <= sqrt(n) and i divides n, then n/i is the corresponding larger divisor.
Approach
- For
ifrom1tofloor(sqrt(n)):- If
n % i == 0: outputi.- If
n / i != i, also outputn / i(this prints a large counterpart).
- If
- If
Note: output order is not sorted (small then its paired large), producing a zig-zag pattern.
Code
C++
class Solution {
public:
static void printDivisorsPairs(int n) {
int r = (int) std::floor(std::sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) std::printf("%d ", i);
else std::printf("%d %d ", i, n / i);
}
}
}
};
Go
package main
import ("fmt"; "math")
func PrintDivisorsPairs(n int) {
r := int(math.Floor(math.Sqrt(float64(n))))
for i := 1; i <= r; i++ {
if n%i == 0 {
if n/i == i { fmt.Printf("%d ", i) } else { fmt.Printf("%d %d ", i, n/i) }
}
}
}
Java
class Solution {
public static void printDivisorsPairs(int n) {
int r = (int)Math.floor(Math.sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) System.out.printf("%d ", i);
else System.out.printf("%d %d ", i, n / i);
}
}
}
}
Kotlin
object Solution {
fun printDivisorsPairs(n: Int) {
val r = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in 1..r) {
if (n % i == 0) {
if (n / i == i) print("$i ") else print("$i ${n / i} ")
}
}
}
}
Python
class Solution:
def print_divisors_pairs(self, n: int) -> None:
r = int(n**0.5)
for i in range(1, r+1):
if n % i == 0:
if n // i == i:
print(i, end=' ')
else:
print(i, n//i, end=' ')
Rust
pub struct Solution;
impl Solution {
pub fn print_divisors_pairs(n: i64) {
let r = (n as f64).sqrt().floor() as i64;
for i in 1..=r {
if n % i == 0 {
if n / i == i { print!("{} ", i); } else { print!("{} {} ", i, n / i); }
}
}
}
}
Complexity
- ⏰ Time complexity:
O(sqrt(n))— loop up tosqrt(n). - 🧺 Space complexity:
O(1).
Method 3 — Print divisors in sorted order (recommended)
Intuition
Collect the small divisors while iterating up to sqrt(n) and save their large counterparts; then print small divisors followed by the reversed list of large divisors to produce a sorted sequence.
Approach
- Initialize an empty list
highs. - For
ifrom1tofloor(sqrt(n)):- If
n % i == 0:- If
n / i == i, printi. - Else: print
iand appendn / itohighs.
- If
- If
- After the loop, iterate
highsin reverse and print each element.
Code
C++
#include <vector>
class Solution {
public:
static void printDivisorsSorted(int n) {
std::vector<int> highs;
int r = (int) std::floor(std::sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) std::printf("%d ", i);
else { std::printf("%d ", i); highs.push_back(n / i); }
}
}
for (int i = (int)highs.size() - 1; i >= 0; --i) std::printf("%d ", highs[i]);
}
};
Go
package main
import ("fmt"; "math")
func PrintDivisorsSorted(n int) {
highs := []int{}
r := int(math.Floor(math.Sqrt(float64(n))))
for i := 1; i <= r; i++ {
if n%i == 0 {
if n/i == i { fmt.Printf("%d ", i) }
else { fmt.Printf("%d ", i); highs = append(highs, n/i) }
}
}
for i := len(highs)-1; i >= 0; i-- { fmt.Printf("%d ", highs[i]) }
}
Java
import java.util.*;
class Solution {
public static void printDivisorsSorted(int n) {
List<Integer> highs = new ArrayList<>();
int r = (int)Math.floor(Math.sqrt(n));
for (int i = 1; i <= r; ++i) {
if (n % i == 0) {
if (n / i == i) System.out.printf("%d ", i);
else { System.out.printf("%d ", i); highs.add(n / i); }
}
}
for (int i = highs.size() - 1; i >= 0; --i) System.out.printf("%d ", highs.get(i));
}
}
Kotlin
object Solution {
fun printDivisorsSorted(n: Int) {
val highs = mutableListOf<Int>()
val r = kotlin.math.sqrt(n.toDouble()).toInt()
for (i in 1..r) {
if (n % i == 0) {
if (n / i == i) print("$i ") else { print("$i "); highs.add(n / i) }
}
}
for (i in highs.size - 1 downTo 0) print("${highs[i]} ")
}
}
Python
class Solution:
def print_divisors_sorted(self, n: int) -> None:
highs = []
r = int(n**0.5)
for i in range(1, r+1):
if n % i == 0:
if n // i == i:
print(i, end=' ')
else:
print(i, end=' ')
highs.append(n//i)
for x in reversed(highs): print(x, end=' ')
Rust
pub struct Solution;
impl Solution {
pub fn print_divisors_sorted(n: i64) {
let mut highs: Vec<i64> = Vec::new();
let r = (n as f64).sqrt().floor() as i64;
for i in 1..=r {
if n % i == 0 {
if n / i == i { print!("{} ", i); }
else { print!("{} ", i); highs.push(n / i); }
}
}
for &x in highs.iter().rev() { print!("{} ", x); }
}
}
Complexity
- ⏰ Time complexity:
O(sqrt(n))— iterate up tosqrt(n). - 🧺 Space complexity:
O(sqrt(n))for storing large divisors in worst-case (Method 3).