## Improved power recursive function

recursive power function java

recursive power function time complexity

recursive power function python

recursive power function javascript

iterative power function

time complexity of power function

recursive function for exponentiation

I'm trying to write a recursive function to elevate one number to the power of another where x^n=(x^(n/2)^2 if n is even or x^n=x*(x^(n-1)) if n is odd.

I've been thinking about it for quite a while and tried a few things but honestly I don't know how to approach the problem, especially if n is odd. I've written a bit of code in case n is even but I don't even know if it would make sense to post it as the logic behind it is pretty broken itself.

Any help appreciated!

int power(int x, int n){ int result = 1; if(n % 2 == 0){ n /= 2; for(; n > 0; n--){ result *= x; } power(result, 2); } return result; }

2nd try, no for loops:

int power(int x, int n){ int result = 1; if(n % 2 == 0){ result *= x; power(x, n / 2); } return result; }

Here's a literal translation of "x^n=(x^(n/2)^2 if n is even or x^n=x*(x^(n-1)) if n is odd" using recursion:

int power(int x, int n){ int temp; if(n % 2 == 0){ // n is even temp = power(x, n / 2); return temp * temp; } else { // n is odd return x * power(x, n - 1); } }

Note that this code is deliberately wrong (will probably recurse "forever" and cause a stack overflow) because the original description didn't include special handling for the `n = 0`

case.

For a more correct/less literal version:

int power(int x, int n){ int temp; if(n % 2 == 0){ // n is even if(n == 0) { return 1; } temp = power(x, n / 2); return temp * temp; } else { // n is odd return x * power(x, n - 1); } }

Of course this is relatively awful (for readability/maintainability and performance) because the requirements are awful. A version that ignores the requirements (and isn't recursive) would be:

int power(int x, int n){ int result = 1; while(n > 0) { if( (n & 1) != 0) { result *= x; } n >>= 1; x *= x; } return result; }

**OFF-TOPIC ADDENDUM**

For calculating powers, if you convert the exponent into binary you can use each binary digit as a flag to determine whether or not to multiply the result with the "squared each iteration" temporary value. For example, `x**5`

is the same as `(x**4) * (x**1)`

because `5 == 101b`

.

**This is important/useful when you need to handle fractional exponents.** For example, `x**5.5`

is the same as `(x**4) * (x**1) * (x**0.5)`

because `5.5 == 101.1b`

.

In other words, starting from the exponent's decimal point and going towards the most significant bit through the integer part of the exponent you can `if(next bit of exponent was set) { result *= temp}; temp *= temp;`

; and starting from the exponents decimal point and going towards the least significant bit through the fractional portion of the exponent you can `if(next bit of exponent was set) { result *= temp}; temp = sqrt(temp);`

.

When I first wrote this answer the last example code was written using the "convert exponent to binary digits" method I've described here, with no regard to the "x^n=(x^(n/2)^2 if n is even or x^n=x*(x^(n-1)) if n is odd" in the original question. It wasn't until later that I realised that the approach in the original question ends up being equivalent code from a different perspective.

**Recursive power function: approach,** When rewriting your function, don't lose sight of the main benefit of recursion in this case, which is to reduce the number of multiplication operations required. This also means that power(1, 2) also leads to power (1, 2) after a certain number of recursions. Thus, this power() within a power() leads to an infinite recursion and thus the stack overflow. Now, to your question. Yes, this can be done without using pow() because pow(a, 2) can simply be written as a*a. So, here is a slight modification to

**Improved power recursive function,** recursive power function java recursive power function python recursive power function c power using recursion geeksforgeeks c++ program to find power of a Recursive program to generate power set. Given a set represented as string, write a recursive code to print all subsets of it. The subsets can be printed in any order. Examples: Input : set = "abc" Output : "". "a", "b", "c", "ab", "ac", "bc", "abc" Input : set = "abcd" Output : "" "a" "ab" "abc" "abcd" "abd" "ac" "acd" "ad" "b" "bc" "bcd" "bd" "c" "cd" "d".

#include <stdio.h> int power(int n1, int n2); int main() { int base, powerRaised, result; printf("Enter base number: "); scanf("%d",&base); printf("Enter power number(positive integer): "); scanf("%d",&powerRaised); result = power(base, powerRaised); printf("%d^%d = %d", base, powerRaised, result); return 0; } int power(int base, int powerRaised) { if (powerRaised != 0) return (base*power(base, powerRaised-1)); else return 1; }

**Efficiently implement power function,** Given two integers x and n where n is non-negative, efficiently compute the value of power function pow(x, n) using Divide & Conquer. A simple solution to They are present in the M language for Power BI / Power Query and this is a post where I’ll go over how to use recursion or make recursive functions in Power BI / Power Query. This is a pretty advanced topic on Power BI / Power Query and the M language.

**C++ Program to Calculate Power Using Recursion,** To find power of any number, you can use pow() function. result = pow(base, exponent);. Share on:. Given two integers x and n where n is non-negative, efficiently compute the value of power function pow(x, n) using Divide & Conquer. A simple solution to calculate pow(x, n) would be multiply x exactly n times. We can do that by using simple for loop. The time complexity of this solution is O(n).

**C program to calculate the power using recursion,** example, you will learn to calculate the power of a number using recursion. of a number raised to a decimal value, you can use the pow() library function. C++ Program to Calculate Power Using Recursion This program calculates the power of a number using recursion where base and exponent is entered by the user. To understand this example, you should have the knowledge of the following C++ programming topics:

**Write a program to calculate pow(x,n),** Function to calculate x raised to the power y */. public : int power( int x, unsigned int y). {. if (y == 0). return 1;. else if (y % 2 == 0). return power(x, y / 2) * power(x, However, custom functions coupled with a somewhat little-known capability of Power Query's "M" language, recursion, can help us solve this problem. Base Function. The first function that we will need is a way to translate hexadecimal values or other bases to decimal. We can do this with a custom function, fnHex2Dec like below:

##### Comments

- Writing a recursive function to calculate an arbitrary exponent isn't challenging. We're not here to write code for you; why not post your best try and we can take it from there.
- @DavidHoelzer just updated with my code. I wasn't expecting anyone to write anything for me, just a little tip on the reasoning behind it ahah anyways I know my code is broken but I can't find any better solution
- You call your function recursively to evaluate something; you ignore the value that's returned. This seems likely to give problems. I'm not clear why you want a recursive function — the iterative code is simple and sufficient.
- You have no base case in your recursion, so you recurse infinitely.
- The code you've written doesn't match the algorithm you've described. What you've described doesn't need any loops, just recursive calls and multiplication. Also, you don't have a base case for
`n == 2`

; you should define a special case for that, like`x * x`

. - The requirements for recursive functions are always awful; there are legitimate uses for recursion but they aren't simple as teaching aids. You shouldn't calculate this or factorial using recursion (in a C-like language; if you're using a functional language things are different), and you shouldn't even use a loop for Fibonacci. However, I would like to point out that for modern compilers,
`>>= 1`

is exactly equivalent to`/= 2`

, and the latter is generally more readable. Similarly for`n & 1`

and`n % 2`

, I'd go with the readable option and hope the compiler isn't stupid. - @DanielH: For the last version, I see it as converting
`n`

to binary where shifts and AND are more natural for extracting bits. There's logical reasons for this, but it's hard to fit an explanation into a comment due to the "number of characters" limit - will "cheat" and add an off-topic section to my answer (in the hope that people don't mind too much that I probably shouldn't given that it should be educational for those interested). - Yeah, thinking of it that way it makes complete sense to do it that way. I think there should be an off topic section to explain why; I only understand your comment because I've seen it that way before and just didn't get it from the code.
- The last
`power(int x, int n)`

has troubles when 1)`result`

is in`int`

range, yet`x *= x`

overflows (UB). 2) rare non-2's complement platforms. 3)`n < 0`

. The recursive version does not have problems #1, #2 and fewer #3 problems. Certainly better defined code should we move to`unsigned n`

. - @chux: I"m just using the same signature as the OP (
`int power(int, int)`

) - the nature of`pow()`

means that it's likely to overflow with relatively small inputs regardless of what you do (unless you use floating point or big numbers - e.g.`double power(int, int)`

). It's trivial to add support for negative exponents (e.g.`if(n < 0) return 1/power(x, -n);`

) but that isn't particularly useful if you're using any integer type. Negative bases should work for all versions. - Note:
`x^n = x*(x^(n-1))`

makes sense when`n>=0`

. IMO, rather than try and fix code to cope with`n < 0`

, better to use`unsigned n`

. - This still uses the wrong algorithm, and you should explain what you're doing and why instead of just providing code, but if you fix that you should do so by editing instead of just posting a new answer.