1

I simply want to test something. I am wondering what I did wrong?

   #include <iostream>
   using namespace std;
   unsigned long pwr(unsigned long n, unsigned long m)
   {
          if(m == 0)
            n = 1;
          if(m == 1)
            n = n;
          n = pwr(n, m/2) * pwr(n, m/2);
          return n;
   }

   int main ()
   {
          unsigned long n(2), m(16);
          cout << pwr(n, m);
          return 0;
   }

output is

Segmentation fault
1
  • Have you tried printf debugging to see on what line it fails and how deeply it's recursed? Commented Nov 20, 2011 at 15:20

4 Answers 4

7

There is no exit from recursion.

You may wanted

          if(m == 0)
             n = 1;
          else if(m == 1)
             n = n;
          else 
             n = pwr(n, m/2) * pwr(n, m/2);
          return n;
Sign up to request clarification or add additional context in comments.

Comments

3

Infinite recursion: The recursive call is executed unconditionally, and so the call stack grows until an error stops it.

This is a stack overflow.

Comments

2

You're not ending the recursion when you hit your base case. Even when m == 0 or m == 1 are true, you still recursively call pwr. So you've got infinite recursion.

Comments

-1

you are dividing by 0: let's say m starts from 1, in the next iteration m = 1/2 = 0, and you will get the fault. what you probably want to do it return 1 if m = 0 instead of going through the method.

2 Comments

m is never used as a divisor, only 2 is.
that is not a base since you continue running the method. you need to return something at that point to stop the recursion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.