on-internet
← Community

How to optimize recursive Binary Exponentiation using tail recursion and handle negative exponents without loops in C++?

Stack Overflow ·

I am practicing recursion and divide-and-conquer algorithms in C++ under strict constraints: **no `for` or `while` loops**, no `<cmath>` library, and no compiler optimization pragmas. I have implemented a recursive Binary Exponentiation function ($O(\log n)$ time complexity) for non-negative integers by storing the recursive result in a temporary variable `half` to avoid redundant calls: #include <bits/stdc++.h> using namespace std; long long a, n; long long power (long long a, long long n) { if (n == 0) return 1; long long half = power(a, n / 2); if (n % 2 == 0) { return half * half; } else {

Comments

Sign in or sign up to comment and upvote.

No comments yet.