Recursive algorithm, please help!

Just stucked in this little excercise, compile fine but running and it crashes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

long pow(int, int);

main()
{
    int x, y;
    cout << "Input two number x and y: ";
    cin >> x, y;
    cout << "Result of x^y is " << pow(x, y);
}

long pow(int x, int y)
{
    if (y > 1)
    {
        return x * pow(x, y-1);
    }
    return x;
}
Last edited on
cin >> x, y;

Suppose to be

cin >> x >> y;
Thank, it worked. ^^
You should take into account the case when y is equal to 0. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
	struct pow
	{
		long long operator ()( int x, unsigned int y ) const
		{
			if ( y ) return ( x * ( *this )( x, --y ) );
			else return ( 1 );
		}
	};

	std::cout << "2 ^ 4 = " << pow()( 2, 4 ) << std::endl;
}
Last edited on
Topic archived. No new replies allowed.