Find smallest perfect square number A such that N + A is also a perfect square number | Python3 code to find out the smallest perfect square X which when added to N yields another perfect square number . ; X is the smallest perfect square number ; Loop from 1 to square root of N ; Condition to check whether i is factor of N or not ; Condition to check whether factors satisfies the equation or not ; Stores minimum value ; Return if X * X if X is not equal to 1e9 else return - 1 ; Driver code
import math NEW_LINE def SmallestPerfectSquare ( N ) : NEW_LINE INDENT X = 1e9 NEW_LINE for i in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if N % i == 0 : NEW_LINE INDENT a = i NEW_LINE b = N // i NEW_LINE if b - a != 0 and ( b - a ) % 2 == 0 : NEW_LINE INDENT X = min ( X , ( b - a ) // 2 ) NEW_LINE DEDENT DEDENT DEDENT return ( X * X if X != 1e9 else - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( SmallestPerfectSquare ( N ) ) NEW_LINE DEDENT