VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-the-nearest-prime-number-formed-by-adding-prime-numbers-to-n/

⇱ Print the nearest prime number formed by adding prime numbers to N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the nearest prime number formed by adding prime numbers to N

Last Updated : 11 Jul, 2025

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.

  • First run the loop from 2 to N*N and find a prime number.
  • Then add that prime number to variable sum and check then the new sum formed is prime or not.
  • If it is a Prime Number then return sum and if not then find another prime number and perform the same task again until sum become a prime number.

Implementation :


Output
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: 
 


Output
13

Time Complexity: O(N * log(logN)) 
Auxiliary Space: O(N) 

Comment
Article Tags: