A fast exponentiation algorithm with non-recursive recursion

Source: Internet
Author: User
Tags pow

Fast to the power of the whole number of times, of course, can not directly die. As an example:
3 ^ 999 = 3 * 3 * 3 * ... * 3
Multiply directly by 998 times. But in fact can do this, first find out 2^k power:
3 ^ 2 = 3 * 3
3 ^ 4 = (3 ^ 2) * (3 ^ 2)
3 ^ 8 = (3 ^ 4) * (3 ^ 4)
3 ^ 16 = (3 ^ 8) * (3 ^ 8)
3 ^ 32 = (3 ^ 16) * (3 ^ 16)
3 ^ 64 = (3 ^ 32) * (3 ^ 32)
3 ^ 128 = (3 ^ 64) * (3 ^ 64)
3 ^ 256 = (3 ^ 128) * (3 ^ 128)
3 ^ 512 = (3 ^ 256) * (3 ^ 256)
Multiply again:
3 ^ 999 = 3 ^ (512 + 256 + 128 + 64 + 32 + 4 + 2 + 1)
= (3 ^ 512) * (3 ^ 256) * (3 ^ 128) * (3 ^ 64) * (3 ^ 32) * (3 ^ 4) * (3 ^ 2) * 3
So just do the multiplication 16 times. Even with some auxiliary storage and operations, it is much more efficient than direct multiplication (especially if the base is a large number of hundreds of thousands of digits).
We found that to convert 999 to 2 binary number: 1111100111, and all of them are to multiply the number. This suggests that we use the BITS algorithm (where mod is a modulo operation):

So you can write the following code:

Double Pow (doubleint  n) {    double1;      while (n)    {        if1)        //equivalent to if (n% 2! = 0            )*= x        ; 1 ;         *= x;    }     return result;}

Finally test the comparison with the POW function in the C standard library function:

#include <stdio.h>#include<math.h>#include<time.h>using namespacestd;#defineCOUNT 100000000DoublePow (DoubleXintN) {    Doubleresult =1;  while(n) {if(N &1) Result*=x; N>>=1; X*=x; }    returnresult;}intMain () {intstart, end; Start=clock ();  for(inti =0; i < COUNT; i++) Pow (2.0, -); End=clock (); printf ("Time =%d\n", (End-start)); Start=clock ();  for(inti =0; i < COUNT; i++) Pow (2.0,100.0); End=clock (); printf ("Time =%d\n", (End-start)); return 0;}

The end result is about the same.

A fast exponentiation algorithm with non-recursive recursion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.