When B is large, use thisAlgorithmIs the best choice. It is often used in cryptography:
Code:
/* File: ABN. cdescription: Generic algorithm for finding a's B power modulo n Author: hanxi */ # Include <Stdio. h> # Include <Math. h> Int F ( Int A, Int B, Int N ){ Int C =0 , D = 1 ; Int I; For (I = 31 ; I> = 0 ; I -- ) {D = (D * D) % N; c * = 2 ; Int TMP; TMP = 1 < I; // Printf ("tmp = % d \ n", TMP ); If (B & TMP )! = 0 ) {D = (D * A) % N; c ++ ;}} Return D ;} Int Main (){ Int A = 2 , B =5 , N = 10 ; Printf ( " Evaluate the power-B modulo n \ n of " ); Printf ( " Enter a, B, n (separated by commas (,). If a, B, and n are all 0, exit the system ): " ); Scanf ( " % D, % d, % d " , & A, & B ,& N); printf ( " A = % d, B = % d, n = % d \ n " , A, B, n ); While (! = 0 & B! = 0 & N! = 0 ){ Int D = F (a, B, n); printf ( " % D power modulo % d = % d \ n of % d " , A, B, n, d ); Int X =Pow (a, B); printf ( " % D power modulo % d = % d \ n of % d " , A, B, n, x % N); printf ( " Enter a, B, and B (separated by commas ): " ); Scanf ( " % D, % d, % d " , & A, & B ,& N); printf ( " A = % d, B = % d, n = % d \ n " , A, B, n);} printf ( " ProgramEnded... " ); Return 1 ;}