Now I know that the error "Segmentation fault (core dumped)" means that I have a pointer in my code pointing to memory it isn't authorized to access. But the problem is I don't even have a pointer in the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <cmath>
usingnamespace std;
int power3(int p, int q){
if (q == 0) return 1;
if (q == 1) return p;
if (q%2 == 0) return p * power3((power3(p,(q/2))),2);
elseif (q%2 != 0) return p * power3((power3(p,((q-1)/2))),2);
}
int main(){
int a, b;
cin >> a;
cin >> b;
cout << power3(a, b);
return 0;
}
I'm thinking the only thing that could be responsible is line 8 or 9, or both. I tried as much as I could to fix it. Does anyone have an idea of what to do?
You have an infinite loop. Consider what happens when you encounter the following code: power3((power3(p,(q/2))),2); // line 8
using the input: p = 5, q = 2
1 2 3 4 5
...
if (q % 2 == 0)
// inner function executes: power3(5, 1); and returns p
// outer function executes: power(5, 2)
// Uh oh looks like we are back to where we started
I am not trying to show that your code produces an infinite loop with the given input, I'm instead trying to draw your attention to the constants you leave unhandled in your function calls
The function will still not work if q is not 2. Let's take that example again with p = 5 and now q = 3
1 2 3 4
elseif (q % 2 != 0)
// inner function executes with power3(5, (3 - 1)/2 = 1); and returns p
// outer function executes with power3(5, 2);
// infinite loop again
I'm really sorry, I should've posted in the beginners forum. I just don't understand why the function loops over and over. I've been trying but I can't seem to think of anything that I can do. I understand how it loops if q = 2 || 3, but if q = 8 then shouldn't it be able to work?
> I understand how it loops if q = 2 || 3,
> but if q = 8 then shouldn't it be able to work?
then you didn't understand.
for q \notin {0,1} you will call power3(_, 2)