Hello all,
I'm just starting out and learning Java right now, so please bear with me =) I'm working on a school assignment that asks me write two methods, one iterative and the other recursive. I have no problem creating the iterative but the subject of recursion has always been kinda hazy to me. I have a working recursive method but I get stack overflow errors. Here's the code I have right now:
Basically what the program does is take in three arguments (x, y, and z) and computes X to the power of y, then the mod of z. So the equation looks like (x^y)mod z. I'm not quite sure if this is enough information, it it isn't just let me know. Can anyone show me how to implement recursion in this particular instance? Any help is appreciated.
Thanks,
Jisoo22
I'm just starting out and learning Java right now, so please bear with me =) I'm working on a school assignment that asks me write two methods, one iterative and the other recursive. I have no problem creating the iterative but the subject of recursion has always been kinda hazy to me. I have a working recursive method but I get stack overflow errors. Here's the code I have right now:
Code:
public long powerMod1( long x, long y, long n ) {
long temp = 1;
long temp2 = 0;
for (int i = 1; i <= y; i++)
{
temp = temp * x;
temp2 = temp % n;
}
return temp2;
}
//powerMod2 method goes below
public long powerMod2( long x, long y, long n ) {
long temp;
long temp2 = powerMod2( x, y-1, n);
if (y == 1)
return x%n;
else
temp = (x%n * temp2)%n;
return temp;
}
Basically what the program does is take in three arguments (x, y, and z) and computes X to the power of y, then the mod of z. So the equation looks like (x^y)mod z. I'm not quite sure if this is enough information, it it isn't just let me know. Can anyone show me how to implement recursion in this particular instance? Any help is appreciated.
Thanks,
Jisoo22