Program For Closest Prime Number
Last Updated :
19 Mar, 2023
Given a number N, you have to print its closest prime number. The prime number can be lesser, equal, or greater than the given number.
Condition: 1 ≤ N ≤ 100000
Examples:
Input : 16
Output: 17
Explanation: The two nearer prime number of 16 are 13 and 17. But among these,
17 is the closest(As its distance is only 1(17-16) from the given number).
Input : 97
Output : 97
Explanation : The closest prime number in this case is the given number number
itself as the distance is 0 (97-97).
Approach :
- Using Sieve of Eratosthenes store all prime numbers in a Vector.
- Copy all elements in vector to the new array.
- Use the upper bound to find the upper bound of the given number in an array.
- As the array is already sorted in nature, compare previous and current indexed numbers in an array.
- Return number with the smallest difference.
Below is the implementation of the approach.
C++
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 100005;
vector<int> primeNumber;
// Sieve of Eratosthenes algorithm to find all prime numbers up to MAX
void sieveOfEratosthenes() {
// Create a boolean array "prime[0..n]" and initialize all entries as true.
// A value in prime[i] will finally be false if i is not a prime, else true.
bool prime[MAX + 1];
for (int i = 0; i <= MAX; i++) {
prime[i] = true;
}
// Update all multiples of p
for (int p = 2; p * p <= MAX; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
for (int i = p * p; i <= MAX; i += p) {
prime[i] = false;
}
}
}
// Add all prime numbers to the vector
for (int i = 2; i <= MAX; i++) {
if (prime[i] == true) {
primeNumber.push_back(i);
}
}
}
// Binary search to find the index of the smallest element greater than number
int upper_bound(vector<int> arr, int low, int high, int number) {
// Base case
if (low > high) {
return low;
}
// Find the middle index
int mid = low + (high - low) / 2;
// If arr[mid] is less than or equal to number, search in the right subarray
if (arr[mid] <= number) {
return upper_bound(arr, mid + 1, high, number);
}
// If arr[mid] is greater than number, search in the left subarray
return upper_bound(arr, low, mid - 1, number);
}
// Function to find the closest prime number to a given number
int closestPrime(int number) {
// Handle special case of number 1 explicitly
if (number == 1) {
return 2;
}
else {
// Generate all prime numbers using Sieve of Eratosthenes algorithm
sieveOfEratosthenes();
// Convert vector to array for binary search
int n = primeNumber.size();
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = primeNumber[i];
}
// Find the index of the smallest element greater than number
int index = upper_bound(primeNumber, 0, n, number);
// Check if the current element or the previous element is the closest
if (arr[index] == number || arr[index - 1] == number) {
return number;
}
else if (abs(arr[index] - number) < abs(arr[index - 1] - number)) {
return arr[index];
}
else {
return arr[index - 1];
}
}
}
// Driver program to test the above function
int main() {
int number = 100;
cout << closestPrime(number) << endl;
return 0;
}
Java
// Closest Prime Number in Java
import java.util.*;
import java.lang.*;
public class GFG {
static int max = 100005;
static Vector<Integer> primeNumber = new Vector<>();
static void sieveOfEratosthenes()
{
// Create a boolean array "prime[0..n]" and
// initialize all entries it as true. A value
// in prime[i] will finally be false if i is
// Not a prime, else true.
boolean prime[] = new boolean[max + 1];
for (int i = 0; i <= max; i++)
prime[i] = true;
for (int p = 2; p * p <= max; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * p; i <= max; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= max; i++) {
if (prime[i] == true)
primeNumber.add(i);
}
}
static int upper_bound(Integer arr[], int low, int high,
int X)
{
// Base Case
if (low > high)
return low;
// Find the middle index
int mid = low + (high - low) / 2;
// If arr[mid] is less than
// or equal to X search in
// right subarray
if (arr[mid] <= X) {
return upper_bound(arr, mid + 1, high, X);
}
// If arr[mid] is greater than X
// then search in left subarray
return upper_bound(arr, low, mid - 1, X);
}
public static int closetPrime(int number)
{
// We will handle it (for number = 1) explicitly
// as the lower/left number of 1 can give us
// negative index which will cost Runtime Error.
if (number == 1)
return 2;
else {
// calling sieve of eratosthenes to
// fill the array into prime numbers
sieveOfEratosthenes();
Integer[] arr = primeNumber.toArray(
new Integer[primeNumber.size()]);
// searching the index
int index
= upper_bound(arr, 0, arr.length, number);
if (arr[index] == number
|| arr[index - 1] == number)
return number;
else if (Math.abs(arr[index] - number)
< Math.abs(arr[index - 1] - number))
return arr[index];
else
return arr[index - 1];
}
}
// Driver Program
public static void main(String[] args)
{
int number = 100;
System.out.println(closetPrime(number));
}
}
Python3
# python code for the above approach
import bisect
import math
MAX = 100005
prime_numbers = []
# Sieve of Eratosthenes algorithm to find all prime numbers up to MAX
def sieve_of_eratosthenes():
# Create a boolean array "prime[0..n]" and initialize all entries as true.
# A value in prime[i] will finally be false if i is not a prime, else true.
prime = [True] * (MAX + 1)
# Update all multiples of p
for p in range(2, int(math.sqrt(MAX)) + 1):
# If prime[p] is not changed, then it is a prime
if prime[p]:
for i in range(p * p, MAX + 1, p):
prime[i] = False
# Add all prime numbers to the list
for i in range(2, MAX + 1):
if prime[i]:
prime_numbers.append(i)
# Function to find the closest prime number to a given number
def closest_prime(number):
# Handle special case of number 1 explicitly
if number == 1:
return 2
else:
# Generate all prime numbers using Sieve of Eratosthenes algorithm
sieve_of_eratosthenes()
# Find the index of the smallest element greater than number
index = bisect.bisect_left(prime_numbers, number)
# Check if the current element or the previous element is the closest
if prime_numbers[index] == number or prime_numbers[index - 1] == number:
return number
elif abs(prime_numbers[index] - number) < abs(prime_numbers[index - 1] - number):
return prime_numbers[index]
else:
return prime_numbers[index - 1]
# Driver program to test the above function
if __name__ == '__main__':
number = 100
print(closest_prime(number))
JavaScript
const MAX = 100005;
let primeNumber = [];
// Sieve of Eratosthenes algorithm to find all prime numbers up to MAX
function sieveOfEratosthenes() {
// Create a boolean array "prime[0..n]" and initialize all entries as true.
// A value in prime[i] will finally be false if i is not a prime, else true.
let prime = Array(MAX + 1).fill(true);
// Update all multiples of p
for (let p = 2; p * p <= MAX; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
for (let i = p * p; i <= MAX; i += p) {
prime[i] = false;
}
}
}
// Add all prime numbers to the vector
for (let i = 2; i <= MAX; i++) {
if (prime[i] == true) {
primeNumber.push(i);
}
}
}
// Binary search to find the index of the smallest element greater than number
function upper_bound(arr, low, high, number) {
// Base case
if (low > high) {
return low;
}
// Find the middle index
let mid = low + Math.floor((high - low) / 2);
// If arr[mid] is less than or equal to number, search in the right subarray
if (arr[mid] <= number) {
return upper_bound(arr, mid + 1, high, number);
}
// If arr[mid] is greater than number, search in the left subarray
return upper_bound(arr, low, mid - 1, number);
}
// Function to find the closest prime number to a given number
function closestPrime(number) {
// Handle special case of number 1 explicitly
if (number == 1) {
return 2;
} else {
// Generate all prime numbers using Sieve of Eratosthenes algorithm
sieveOfEratosthenes();
// Find the index of the smallest element greater than number
let index = upper_bound(primeNumber, 0, primeNumber.length, number);
// Check if the current element or the previous element is the closest
if (primeNumber[index] == number || primeNumber[index - 1] == number) {
return number;
} else if (Math.abs(primeNumber[index] - number) < Math.abs(primeNumber[index - 1] - number)) {
return primeNumber[index];
} else {
return primeNumber[index - 1];
}
}
}
// Driver program to test the above function
let number = 100;
console.log(closestPrime(number));
C#
//C# code for the above approach
using System;
using System.Collections.Generic;
public class Program
{
const int MAX = 100005;
static List<int> prime_numbers = new List<int>();
// Sieve of Eratosthenes algorithm to find all prime numbers up to MAX
static void sieve_of_eratosthenes()
{
// Create a boolean array "prime[0..n]" and initialize all entries as true.
// A value in prime[i] will finally be false if i is not a prime, else true.
bool[] prime = new bool[MAX + 1];
for (int i = 0; i <= MAX; i++)
{
prime[i] = true;
}
// Update all multiples of p
for (int p = 2; p <= Math.Sqrt(MAX); p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p])
{
for (int i = p * p; i <= MAX; i += p)
{
prime[i] = false;
}
}
}
// Add all prime numbers to the list
for (int i = 2; i <= MAX; i++)
{
if (prime[i])
{
prime_numbers.Add(i);
}
}
}
// Function to find the closest prime number to a given number
static int closest_prime(int number)
{
// Handle special case of number 1 explicitly
if (number == 1)
{
return 2;
}
else
{
// Generate all prime numbers using Sieve of Eratosthenes algorithm
sieve_of_eratosthenes();
// Find the index of the smallest element greater than number
int index = prime_numbers.BinarySearch(number);
if (index < 0)
{
index = ~index;
}
// Check if the current element or the previous element is the closest
if (prime_numbers[index] == number || prime_numbers[index - 1] == number)
{
return number;
}
else if (Math.Abs(prime_numbers[index] - number) < Math.Abs(prime_numbers[index - 1] - number))
{
return prime_numbers[index];
}
else
{
return prime_numbers[index - 1];
}
}
}
// Driver program to test the above function
public static void Main()
{
int number = 100;
Console.WriteLine(closest_prime(number));
}
}
//This code is contributed by shivamsharma215
Time Complexity: O(N log(log(N)))
Auxiliary Space: O(N)
Similar Reads
Prime Number Program in Java A prime number is a natural number greater than 1, divisible only by 1 and itself. Examples include 2, 3, 5, 7, and 11. These numbers have no other factors besides themselves and one.In this article, we will learn how to write a prime number program in Java when the input given is a Positive number.
6 min read
Java Program to Display All Prime Numbers from 1 to N For a given number N, the purpose is to find all the prime numbers from 1 to N.Examples: Input: N = 11Output: 2, 3, 5, 7, 11Input: N = 7Output: 2, 3, 5, 7 Approach 1:Firstly, consider the given number N as input.Then apply a for loop in order to iterate the numbers from 1 to N.At last, check if each
4 min read
Minimum absolute difference of a number and its closest prime Given a positive integer N, the task is to find the absolute difference of N and the prime number closest to N . Note: The closest prime to N can be either less than, equal to or greater than N.Examples: Input: N = 25 Output: 2 For N = 25 Closest prime greater than 25 is 29. So difference is 4. Clos
8 min read
Java Program to Implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range A number which is divisible by 1 and itself or a number which has factors as 1 and the number itself is called a prime number. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so. Example: Input : from = 1, to = 20 Out
3 min read
Program to check for Twin Prime Numbers A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime
6 min read