Writing power function for large numbers | This function multiplies x with the number represented by res [ ] . res_size is size of res [ ] or number of digits in the number represented by res [ ] . This function uses simple school mathematics for multiplication . This function may value of res_size and returns the new value of res_size ; Initialize carry ; One by one multiply n with individual digits of res [ ] ; Store last digit of ' prod ' in res [ ] ; Put rest in carry ; Put carry in res and increase result size ; This function finds power of a number x ; printing value "1" for power = 0 ; Initialize result ; Multiply x n times ( x ^ n = x * x * x ... . n times ) ; Driver Code
< ? php function multiply ( $ x , $ res ) { $ carry = 0 ; $ res_size = count ( $ res ) ; for ( $ i = 0 ; $ i < $ res_size ; $ i ++ ) { $ prod = $ res [ $ i ] * $ x + $ carry ; $ res [ $ i ] = $ prod % 10 ; $ carry = ( int ) ( $ prod / 10 ) ; } while ( $ carry ) { if ( $ carry % 10 ) $ res [ $ res_size ++ ] = $ carry % 10 ; $ carry = ( int ) ( $ carry / 10 ) ; } return $ res ; } function power ( $ x , $ n ) { if ( $ n == 0 ) { echo "1" ; return ; } $ res_size = 0 ; $ res = array ( ) ; $ temp = $ x ; while ( $ temp != 0 ) { $ res [ $ res_size ++ ] = $ temp % 10 ; $ temp = $ temp / 10 ; } for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ res = multiply ( $ x , $ res ) ; echo $ x . " ^ " . $ n . " ▁ = ▁ " ; $ O = 0 ; for ( $ i = count ( $ res ) - 1 ; $ i >= 0 ; $ i -- , $ O ++ ) if ( $ res [ $ i ] ) break ; for ( $ i = count ( $ res ) - $ O - 1 ; $ i >= 0 ; $ i -- ) echo $ res [ $ i ] ; } $ exponent = 100 ; $ base = 2 ; power ( $ base , $ exponent ) ; ? >