VOOZH about

URL: https://www.geeksforgeeks.org/dsa/least-prime-factor-of-numbers-till-n/

⇱ Least prime factor of numbers till n - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Least prime factor of numbers till n

Last Updated : 26 Apr, 2026

Given a number n, print least prime factors of all numbers from 1 to n. The least prime factor of an integer n is the smallest prime number that divides the number.

Note: We need to print 1 for 1 and 0 for 0 even of 0  

Input: n = 6
Output: [0, 1, 2, 3, 2, 5, 2] 
Explanation:
Number : 0 1 2 3 4 5 6
Least Prime Factor: 0 1 2 3 2 5 2

Input: n = 11
Output: [0, 1, 2, 3, 2, 5, 2, 7, 2, 3, 2, 11]
Explanation:
Number: 0 1 2 3 4 5 6 7 8 9 10 11
Least Prime Factor: 0 1 2 3 2 5 2 7 2 3 2 11

Trying Every Number One by One - O(n * √n) Time and O(n) Space

  • For every number from 1 to n, find its least prime factor by checking divisibility starting from 2 up to its square root.
  • Since any number must have a factor ≤ √i, the first number that divides i is its smallest prime factor, and if no such divisor is found, then the number itself is prime.
  • 1 and 0 are handled separately by assigning it values as 1 and 0 respectively.

Output
0 1 2 3 2 5 2 

Using Sieve of Eratosthenes - O(n * log(n)) Time and O(n) Space

We can use a variation of sieve of Eratosthenes to solve the above problem. 

  • Initialize an array where each number is set to itself, then iterate from 2 to n. if a number i is still equal to its value, it is prime.
  • Since every multiple of i (2i, 3i, 4i...) is divisible by it, those numbers are not prime, so while marking these multiples we assign i as their least prime factor because i is the smallest prime dividing them.
  • Since we only assign when a number is not already marked, the first prime that reaches a number ensures it gets its correct smallest prime factor.

Output
0 1 2 3 2 5 2 
Comment