07 Least Prime Factor
The problem can be found at the following link: Question Link
My Approach
To solve the problem, I have used a simple brute force approach to find the least prime factor for each number up to n
. Here are the steps I followed:
I implemented the
findFactor
function, which takes an integern
as input and returns its least prime factor.Within the
findFactor
function, I first check ifn
is less than 2. If it is, I returnn
itself.Then, I iterate from 2 to the square root of
n
(inclusive) and check ifn
is divisible byi
. If it is, I returni
as the least prime factor.If no prime factor is found in the range, I return
n
as the least prime factor.Finally, I implemented the
leastPrimeFactor
function, which takes an integern
as input and returns a vectorout
containing the least prime factor for each number from 0 ton
.Within the
leastPrimeFactor
function, I initialized the vectorout
with sizen+1
.Then, I iterated from 0 to
n
and assigned the least prime factor of each number to the corresponding index in theout
vector.Finally, I returned the
out
vector.
Time and Auxiliary Space Complexity
Time Complexity:
O(n*sqrt(n))
, wheren
is the given number. This is because for each number from0 to n
, we iterate up to the square root of the number to find its least prime factor.Auxiliary Space Complexity:
O(n)
since we are using a vectorout
of sizen+1
to store the least prime factors for each number.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated