Maximum GCD from Given Product of Unknowns | Function to return the required gcd ; Count the number of times 2 divides p ; Equivalent to p = p / 2 ; ; If 2 divides p ; Check all the possible numbers that can divide p ; If n in the end is a prime number ; Return the required gcd ; Driver code
function max_gcd ( n , p ) { let count = 0 ; let gcd = 1 ; while ( p % 2 == 0 ) { p >>= 1 ; count ++ ; } if ( count > 0 ) gcd *= Math . pow ( 2 , parseInt ( count / n , 10 ) ) ; for ( let i = 3 ; i <= parseInt ( Math . sqrt ( p ) , 10 ) ; i += 2 ) { count = 0 ; while ( p % i == 0 ) { count ++ ; p = parseInt ( p / i , 10 ) ; } if ( count > 0 ) { gcd *= Math . pow ( i , parseInt ( count / n , 10 ) ) ; } } if ( p > 2 ) gcd *= Math . pow ( p , parseInt ( 1 / n , 10 ) ) ; return gcd ; } let n = 3 ; let p = 80 ; document . write ( max_gcd ( n , p ) ) ;