Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print the nearest prime number formed by adding prime numbers to N
Given a number N, if it is not prime, the task is to find the nearest prime number by repeatedly adding prime numbers (starting from 2) to N until we get a prime result.
Input: N=6 Output: 11
Explanation
Since 6 is not prime, we add the first prime number 2 to get 6+2=8. Since 8 is also not prime, we add the next prime number 3 to get 8+3=11. Since 11 is prime, the output is 11.
Syntax
int isPrime(int n); int findNearestPrime(int n);
Algorithm
- Check if the given number N is prime. If yes, return N.
- If not prime, start adding prime numbers (2, 3, 5, 7, ...) one by one to N.
- After adding each prime, check if the result is prime.
- Return the first prime number found.
Example
Here's a complete implementation to find the nearest prime by adding primes −
#include <stdio.h>
int isPrime(int n) {
if (n <= 1) return 0;
if (n <= 3) return 1;
if (n % 2 == 0 || n % 3 == 0) return 0;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return 0;
}
return 1;
}
int findNearestPrime(int n) {
if (isPrime(n)) return n;
int current = n;
int primeToAdd = 2;
while (!isPrime(current)) {
/* Find next prime to add */
while (!isPrime(primeToAdd)) {
primeToAdd++;
}
current += primeToAdd;
primeToAdd++;
}
return current;
}
int main() {
int n = 6;
int result = findNearestPrime(n);
printf("Input: %d<br>", n);
printf("Nearest prime by adding primes: %d<br>", result);
/* Test with another number */
n = 15;
result = findNearestPrime(n);
printf("Input: %d<br>", n);
printf("Nearest prime by adding primes: %d<br>", result);
return 0;
}
Input: 6 Nearest prime by adding primes: 11 Input: 15 Nearest prime by adding primes: 17
How It Works
- The
isPrime()function efficiently checks if a number is prime using trial division. - The
findNearestPrime()function adds consecutive prime numbers (2, 3, 5, 7, ...) to the input until a prime result is found. - For N=6: 6+2=8 (not prime), 8+3=11 (prime) ? result is 11.
- For N=15: 15+2=17 (prime) ? result is 17.
Conclusion
This algorithm systematically adds prime numbers to find the nearest prime. The time complexity depends on how many primes need to be added and the efficiency of primality testing.
Advertisements
