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

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...