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

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...