Minimum absolute difference of a number and its closest prime | C ++ program to find the minimum absolute difference between a number and its closest prime ; Function to check if a number is prime or not ; Function to find the minimum absolute difference between a number and its closest prime ; Variables to store first prime above and below N ; Finding first prime number greater than N ; Finding first prime number less than N ; Variables to store the differences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int N ) { for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) return false ; } return true ; } int getDifference ( int N ) { if ( N == 0 ) return 2 ; else if ( N == 1 ) return 1 ; else if ( isPrime ( N ) ) return 0 ; int aboveN = -1 , belowN = -1 ; int n1 ; n1 = N + 1 ; while ( true ) { if ( isPrime ( n1 ) ) { aboveN = n1 ; break ; } else n1 ++ ; } n1 = N - 1 ; while ( true ) { if ( isPrime ( n1 ) ) { belowN = n1 ; break ; } else n1 -- ; } int diff1 = aboveN - N ; int diff2 = N - belowN ; return min ( diff1 , diff2 ) ; } int main ( ) { int N = 25 ; cout << getDifference ( N ) << endl ; return 0 ; }