Smallest divisor of N closest to X | Java program for the above approach ; Function to find the divisor of N closest to the target ; Iterate till square root of N ; Check if divisors are equal ; Check if i is the closest ; Check if i is the closest ; Check if n / i is the closest ; Print the closest value ; Driver code ; Given N & X ; Function Call
import java . util . * ; class GFG { static void findClosest ( int N , int target ) { int closest = - 1 ; int diff = Integer . MAX_VALUE ; for ( int i = 1 ; i <= ( int ) Math . sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( N / i == i ) { if ( Math . abs ( target - i ) < diff ) { diff = Math . abs ( target - i ) ; closest = i ; } } else { if ( Math . abs ( target - i ) < diff ) { diff = Math . abs ( target - i ) ; closest = i ; } if ( Math . abs ( target - N / i ) < diff ) { diff = Math . abs ( target - N / i ) ; closest = N / i ; } } } } System . out . println ( closest ) ; } public static void main ( String [ ] args ) { int N = 16 , X = 5 ; findClosest ( N , X ) ; } }