Largest factor of a given number which is a perfect square | C ++ 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
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int largestSquareFactor ( int num ) { int answer = 1 ; for ( int i = 2 ; i < sqrt ( num ) ; ++ i ) { int cnt = 0 ; int j = i ; while ( num % j == 0 ) { cnt ++ ; j *= i ; } if ( cnt & 1 ) { cnt -- ; answer *= pow ( i , cnt ) ; } else { answer *= pow ( i , cnt ) ; } } return answer ; } int main ( ) { int N = 420 ; cout << largestSquareFactor ( N ) ; return 0 ; }