Largest factor of a given number which is a perfect square | Python 3 program to find the largest factor of a number which is also a perfect square ; Function to find the largest factor of a given number which is a perfect square ; Initialise the answer to 1 ; Finding the prime factors till sqrt ( num ) ; Frequency of the prime factor in the factorisation initialised to 0 ; If the frequency is odd then multiply i frequency - 1 times to the answer ; Else if it is even , multiply it frequency times ; Driver Code
import math NEW_LINE def largestSquareFactor ( num ) : NEW_LINE INDENT answer = 1 NEW_LINE for i in range ( 2 , int ( math . sqrt ( num ) ) ) : NEW_LINE INDENT cnt = 0 NEW_LINE j = i NEW_LINE while ( num % j == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE j *= i NEW_LINE DEDENT if ( cnt & 1 ) : NEW_LINE INDENT cnt -= 1 NEW_LINE answer *= pow ( i , cnt ) NEW_LINE DEDENT else : NEW_LINE INDENT answer *= pow ( i , cnt ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 420 NEW_LINE print ( largestSquareFactor ( N ) ) NEW_LINE DEDENT