The algorithms to solve the question x ^ n

Source: Internet
Author: User

Algorithm 1: time complexity O (N)

double pow(double x, long n){ if(n==0) return 1; /*when n=0 whatever the x is,the pow is 1*/ if(n==1)     return x;   /*when n=1 the result is x itself*/ else {  double tempa=1.0000;  while(n--) tempa=tempa*x;  return (tempa); /*every time make n-- then multiply a xto get the result*/ }}

Algorithm 2: time complexity O (log (n ))

double pow(double  x, long n){ if(n==0)return 1;   /*when n=0 whatever the x is,the pow is 1*/ if(n==1)  return x; /*when n=1 the result is x itself*/ double temp=1.0; while(n) {if(n%2) temp*=x; /*when n is odd*/x*=x;n/=2; } return temp;}

Algorithm 3: time complexity O (log (n ))

double pow(double x, long n){ if(n==0) return 1;  /*when n=0 whatever the x is,the pow is 1*/ if(n==1)     return x;  /*when n=1 the result is x itself*/ if(n%2==0) return pow(x*x,n/2);  /*when n is an even increase x to x*x and decrease n to n/2*/ else     return pow(x*x,n/2)*x; /*when n is an odd increase x to x*x and decrease n to n/2 an then multiply x*/}

Actually, algorithm 2 is a iterative version of algorithm 3, while algorithm is a recursive version.

Related Article

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.