Smallest divisor of N closest to X | Python3 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 ; Prthe closest value ; Driver Code ; Given N & X ; Function Call
from math import sqrt , floor , ceil NEW_LINE def findClosest ( N , target ) : NEW_LINE INDENT closest = - 1 NEW_LINE diff = 10 ** 18 NEW_LINE for i in range ( 1 , ceil ( sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( N // i == i ) : NEW_LINE INDENT if ( abs ( target - i ) < diff ) : NEW_LINE INDENT diff = abs ( target - i ) NEW_LINE closest = i NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( abs ( target - i ) < diff ) : NEW_LINE INDENT diff = abs ( target - i ) NEW_LINE closest = i NEW_LINE DEDENT if ( abs ( target - N // i ) < diff ) : NEW_LINE INDENT diff = abs ( target - N // i ) NEW_LINE closest = N // i NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( closest ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , X = 16 , 5 NEW_LINE findClosest ( N , X ) NEW_LINE DEDENT