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.
Input: N = 25
For N = 25
Closest prime greater than 25 is 29. So difference is 4.
Closest prime less than 25 is 23. So difference is 2.
The minimum of these two is 2.
Input: N = 2
As 2 itself is a prime number, closest prime number is 2. So difference is 0.
- If N is prime then print 0.
- Else, find the first prime number > N and note its difference with N.
- Then, find the first prime number < N and note its difference with N.
- And print the minimum of these two differences obtained.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the Product of Non-Prime numbers and Prime numbers of an Array
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Pair of prime numbers with a given sum and minimum absolute difference
- Closest perfect square and its distance
- Java Program For Closest Prime Number
- Check whether the sum of absolute difference of adjacent digits is Prime or not
- Minimum number closest to N made up of odd digits only
- Find N numbers such that a number and its reverse are divisible by sum of its digits
- Number of possible permutations when absolute difference between number of elements to the right and left are given
- Minimum absolute difference between N and a power of 2
- Minimum absolute difference between N and any power of 2
- Count prime pairs whose difference is also a Prime Number
- Find sum of a number and its maximum prime factor
- Smallest N digit number with none of its digits as its divisor
- Count of all pairs in an Array with minimum absolute difference
- Minimum absolute difference of server loads
- Split first N natural numbers into two sets with minimum absolute difference of their sums
- Find a pair with sum N having minimum absolute difference
- Find the closest and smaller tidy number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.