Find ( a ^ b ) % m where ' b ' is very large | Java program to find ( a ^ b ) % m for b very large . ; Function to find power ; Update x if it is more than or equal to p ; If y is odd , multiply x with the result ; y must be even now y = y >> 1 ; y = y / 2 ; Driver Code ; String input as b is very large ; Reduce the number B to a small number using Fermat Little
import java . io . * ; class GFG { static long power ( long x , long y , long p ) { x = x % p ; while ( y > 0 ) { if ( ( y & 1 ) > 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } public static void main ( String [ ] args ) { long a = 3 ; String b = "100000000000000000000000000" ; long remainderB = 0 ; long MOD = 1000000007 ; for ( int i = 0 ; i < b . length ( ) ; i ++ ) remainderB = ( remainderB * 10 + b . charAt ( i ) - '0' ) % ( MOD - 1 ) ; System . out . println ( power ( a , remainderB , MOD ) ) ; } }