Pages

Monday, May 26, 2025

X to the Power N(Code) using Recursion in C++

 #include <iostream>

#include <vector>
using namespace std;

int pow(int x, int n) { // O(logn)
    if(n==0) {
        return 1;
    }

    int halfPow = pow(x, n/2);
    int halfPowSquare = halfPow * halfPow;


    if(n%2 != 0) {
        //odd
        return x * halfPowSquare;
    }
    return halfPowSquare;
}

int main() {
    cout << pow(2, 10) << endl;

    return 0;
}


OUTPUT:
1024

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...