I am trying to calculate very large 'long' type numbers using a recursive Exponentiation by Squaring algorithm, as seen below. I am encountering stack overflow errors when increasing the size of the exponent, and I want to find out how I can allow it to loop and not take up so much space on the stack. I want to achieve this without using the Math library, so only in vanilla Java code.
public long exp(long base, long exponent, long accum){
if (power > 0) {
return exp(base, exponent - 1, accum * base);
} else {
return accum;
}
}