![]() |
VOOZH | about |
Given a number N. The task is to print the nearest prime if the number is not prime by making it prime by adding prime numbers sequentially from 2.
Examples:
Input: N = 8
Output: 13
8 is not prime, so add the first prime to it to get 10
10 is not prime, hence add the second prime, i.e., 3 to get 13 which is prime.
Input: N = 45
Output: 47
Naive Approach : In this approach we add every prime number to given number N until we find the desired output.
Implementation :
13
Time Complexity: O((N * N) * N) // run loop from 2 to N*N to find the prime number. and N to check every number is prime or not.
Auxiliary Space: O(1) // no extra space used
Approach Using Sieve of Eratosthenes, mark the prime index by 1 in isprime[] list and store all the prime numbers in a list prime[]. Keep adding prime numbers sequentially to N, till it becomes prime.
Below is the implementation of the above approach:
13
Time Complexity: O(N * log(logN))
Auxiliary Space: O(N)