Least prime factor of numbers till n
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. The least prime factor of all even numbers is 2. A prime number is its own least prime factor (as well as its own greatest prime factor).
Note: We need to print 1 for 1.
Input : 6 Output : Least Prime factor of 1: 1 Least Prime factor of 2: 2 Least Prime factor of 3: 3 Least Prime factor of 4: 2 Least Prime factor of 5: 5 Least Prime factor of 6: 2
We can use a variation of sieve of Eratosthenes to solve the above problem.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Create a list of consecutive integers from 2 through n: (2, 3, 4, …, n).
- Initially, let i equal 2, the smallest prime number.
- Enumerate the multiples of i by counting to n from 2i in increments of i, and mark them as having least prime factor as i (if not already marked). Also mark i as least prime factor of i (i itself is a prime number).
- Find the first number greater than i in the list that is not marked. If there was no such number, stop. Otherwise, let i now equal this new number (which is the next prime), and repeat from step 3.
Below is the implementation of the algorithm, where least_prime saves the value of the least prime factor corresponding to the respective index.
Least Prime factor of 1: 1 Least Prime factor of 2: 2 Least Prime factor of 3: 3 Least Prime factor of 4: 2 Least Prime factor of 5: 5 Least Prime factor of 6: 2 Least Prime factor of 7: 7 Least Prime factor of 8: 2 Least Prime factor of 9: 3 Least Prime factor of 10: 2
Time Complexity: O(nlog(n))
Auxiliary Space: O(n)
Can we extend this algorithm or use least_prime to find all the prime factors for numbers till n?
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.