Using recursion to bring a database to its exponent - C ++

I just want to write code that uses function recursion to raise the base to its power. I know that recursion is not the right way to do something in C ++, but I just want to learn a little about the concept. The program asks the user for the base and the exhibitor, and then the console gives an answer. Here is the program I wrote:

#include <iostream>
#include <math.h>
using namespace std;

int raisingTo(int, int);
int main()
{
    int base, exponent;
    cout << "Enter base value: ";
    cin >> base;
    cout << "Enter exponent value: ";
    cin >> exponent;
    int answer = raisingTo(base, exponent);
    cout << "The answer is: " << answer << endl;
    char response;
    cin >> response;
    return 0;
}

int raisingTo(int base, int exponent)
{
    if (exponent > 0)
        return 1;
    else if (exponent = 0)
    {
        int answer = (int) pow((double)base, raisingTo(base, (exponent - 1)));
        return answer;
    }
}

The funny thing is, when I run this program, it continues to return the answer as "1"! Can someone please help me with this?

0
source share
5 answers
int raisingTo(int base, unsigned int exponent)
{
    if (exponent == 0)
        return 1;
    else
        return base * raisingTo(base, exponent - 1);
}

You have 3 main problems:

  • You do not need to use the pow function
  • , ==, = - , .
  • , 0, 1.
+8

++ - , , .

, , : , .

template <typename NumT>
NumT raiseTo(NumT base, unsigned exponent) {
  if (exponent == 1) return base;
  if (exponent == 0) return 1;
  if (exponent%2 == 0) { NumT ressqrt = raiseTo(base,exponent/2)
                       ; return ressqrt*ressqrt;                  }
  if (exponent%3 == 0) { NumT rescubrt = raiseTo(base,exponent/3)
                       ; return rescubrt*rescubrt*rescubrt;       }
  else return base * raiseTo(base, --exponent);
}

, : , 19. 18 , . :

  • 19 2 3, b ⋅ b e-1
  • 18. 18 2, b e/2
  • 9. 9 3, b e/3
  • 3. 3 3, b e/3
  • b 1 b.

1 + 1 + 2 + 2 = 6 , 1/3 ! , , , . , %3 unsigned, , , int s, NumT==int . , complex, , .

+2

.

if (exponent > 0)
    return 1;
else if (exponent = 0)

-, ( , ), -, if.

+1

(O(lg exponent), O(exponent)), .

int raisingTo(int base const, unsigned int const exponent, int scalar = 1)
{
    if (exponent == 0)
        return scalar;

    if (exponent & 1) scalar *= base;
    return raisingTo(base * base, exponent >> 1, scalar);
}

, .

+1

O (log n)

public int fastPower(int base , int power){

if ( power==0 )
  return 1 
else if(power %2 == 0 )
  return fastPower(base*base,power/2)
else
 return base * fastPower(base,power-1)
}

base^0 = 1
base^power = base*base^(power-1)
base^(2*power) = (base^2)^power

, n , , n. , 1+log n levels

0

All Articles