Pow(x, n)

Implement pow(xn).

C++:
01 double pow(double x, int n) {
02        if(n==0)
03            return 1;
04        if(n==1)
05            return x;
06        bool neg=false;
07        if(n<0){
08            neg=true;
09            n=-n;
10        }
11        double t=pow(x,n/2);
12        t*=t;
13        if(n%2){
14            if(neg)
15                return 1/(x*t);
16            else
17                return x*t;
18        }
19        else{
20            if(neg)
21                return 1/t;
22            else
23                return t;
24        }
25 }
Advertisements
This entry was posted in Divide and Conquer. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s