Given Q queries which consist of two integers, one is number(1 <= number <= 106) and the other is N., the task is to find the N-th prime factor of the given number.
Input: Number of Queries, Q = 4
number = 6, N = 1
number = 210, N = 3
number = 210, N = 2
number = 60, N = 2
6 has prime factors 2 and 3.
210 has prime factors 2, 3 and 6.
60 has prime factors 2 and 3.
A naive approach is to factorize every number and store the prime factors. Print the N-th prime factors thus stored.
Time Complexity: O(log(n)) per query.
An efficient approach is to pre-calculate all the prime factors of the number and store the numbers in a sorted order in a 2-D vector. Since the number will not be more than 106, the number of unique prime factors will be around 7-8 at max(because of 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 >= 106). Once the numbers are stored, the query can be answered in O(1) as the n-1th index will have the answer in numberth row.
Below is the implementation of the above approach:
2 5 3 3
Time Complexity: O(1) per query and O(maxN * log(maxN)) for pre-processing, where maxN = 106.
Auxiliary Space: O(N * 8) in worst case
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- k-th prime factor of a given number
- Find largest prime factor of a number
- Sum of largest prime factor of each number less than equal to n
- Find sum of a number and its maximum prime factor
- Sum of Maximum and Minimum prime factor of every number in the Array
- Exactly n distinct prime factor numbers from a to b
- Queries on the sum of prime factor counts in a range
- Nearest element with at-least one common prime factor
- Count of subarrays whose products don't have any repeating prime factor
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Count all the numbers less than 10^6 whose minimum prime factor is N
- Prime Factor
- Count of distinct power of prime factor of N
- Least prime factor of numbers till n
- Count pairs whose product contains single distinct prime factor
- Find the total number of composite factor for a given number
- Factor Tree of a given Number
- Largest factor of a given number which is a perfect square
- New Algorithm to Generate Prime Numbers from 1 to Nth Number
- Program to find the Nth Prime Number
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.