Modulo power for large numbers represented as strings | Javascript program to find ( a ^ b ) % MOD where a and b may be very large and represented as strings . ; Returns modulo exponentiation for two numbers represented as long long let . It is used by powerStrings ( ) . Its complexity is log ( n ) ; Returns modulo exponentiation for two numbers represented as strings . It is used by powerStrings ( ) ; We convert strings to number ; calculating a % MOD ; calculating b % ( MOD - 1 ) ; Now a and b are long long let . We calculate a ^ b using modulo exponentiation ; As numbers are very large that is it may contains upto 10 ^ 6 digits . So , we use string .
let MOD = ( 1e9 + 7 ) ; function powerLL ( x , n ) { let result = 1 ; while ( n > 0 ) { if ( n % 2 == 1 ) { result = result * x % MOD ; } n = Math . floor ( n / 2 ) ; x = x * x % MOD ; } return result ; } function powerStrings ( sa , sb ) { let a = 0 , b = 0 ; for ( let i = 0 ; i < sa . length ; i ++ ) { a = ( a * 10 + ( sa [ i ] - ' ' ) ) % MOD ; } for ( let i = 0 ; i < sb . length ; i ++ ) { b = ( b * 10 + ( sb [ i ] - ' ' ) ) % ( MOD - 1 ) ; } return powerLL ( a , b ) ; } let sa = " " , sb = " " ; document . write ( powerStrings ( sa , sb ) ) ;