Pow(x, n)

Implement pow(x,n), which calculates x raised to the power n (i.e. xn).

Example:

Input:  x=2, n=2
Output: 4

Approach

Java


public class PowXN {
    public static void main(String[] args) {
        double x = 2;
        int n = 2;
        System.out.println(myPow(x, n));
    }

    static double myPow(double xint n) {
        double temp;
        if (n == 0)
            return 1;
        temp = myPow(x, n / 2);
        if (n % 2 == 0)
            return temp * temp;
        else {
            if (n > 0)
                return x * temp * temp;
            else
                return (temp * temp) / x;
        }
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

double myPow(double xint n
{
    double temp;  
    if(n == 0)  
        return 1;  
    temp = myPow(x, n / 2);  
    if (n % 2 == 0)  
        return temp * temp;  
    else
    {  
        if(n > 0)  
            return x * temp * temp;  
        else
            return (temp * temp) / x;  
    } 
}
int main()
{
  double x=2;
int n=2;
  cout<<myPow(x,n);
  return 0;
}


No comments:

Post a Comment