Find GCD between the sum of two given integers raised to the power of N and their difference | javascript program for the above approach ; Function to find the value of ( a ^ n ) % d ; Stores the value of ( a ^ n ) % d ; Calculate the value of ( a ^ n ) % d ; If n is odd ; Update res ; Update a ; Update n ; Function to find the GCD of ( p ^ n + q ^ n ) and p - q mod d ; If p and q are equal ; Stores GCD of ( p ^ n + q ^ n ) and ( p - q ) mod d ; Stores the value of ( p - q ) ; Stores square root of num ; Find the divisors of num . ; If i divides num ; Stores power of ( p ^ n ) mod i ; Stores power of ( q ^ n ) mod i ; Stores power of ( p ^ n + q ^ n ) mod i ; If ( p ^ n + q ^ n ) is divisible by i ; Calculate the largest divisor . ; If i divides num , ( num / i ) also divides num . Hence , calculate temp . ; If ( p ^ n + q ^ n ) is divisible by ( num / i ) ; Calculate the largest divisor . ; Given p , q and n ; Function Call
const mod = 1000000007 ; function power ( a , n , d ) { var res = 1 ; while ( n != 0 ) { if ( ( n % 2 ) != 0 ) { res = ( ( res % d ) * ( a % d ) ) % d ; } a = ( ( a % d ) * ( a % d ) ) % d ; n /= 2 ; } return res ; } function gcd ( p , q , n ) { if ( p == q ) { return ( power ( p , n , mod ) + power ( q , n , mod ) ) % mod ; } var candidate = 1 ; var num = p - q ; var sq = parseInt ( Math . sqrt ( num ) ) ; for ( i = 1 ; i <= sq ; ++ i ) { if ( num % i == 0 ) { var X = power ( p , n , i ) ; var Y = power ( q , n , i ) ; var temp = ( X + Y ) % i ; if ( temp == 0 ) { candidate = Math . max ( candidate , i ) ; } temp = ( power ( p , n , num / i ) + power ( q , n , num / i ) ) % ( num / i ) ; if ( temp == 0 ) { candidate = Math . max ( candidate , num / i ) ; } } } return candidate % mod ; } var p , q , n ; p = 10 ; q = 6 ; n = 5 ; document . write ( gcd ( p , q , n ) ) ;