-1

I'm trying to solve this problem using recursion, but I seem to run into a stack overflow error beyond a certain divided that's not >= Integer.MAX_VALUE. Could anyone provide some insight into this issue?

class Solution {

int count = 0;

public int divide(int dividend, int divisor) {

    int temp1 = Math.abs(dividend);
    int temp2 = Math.abs(divisor);

    if(dividend > Integer.MAX_VALUE || dividend < Integer.MIN_VALUE){
        if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)){
            System.out.println("executed");
            return Integer.MAX_VALUE;
        }else{
            return Integer.MIN_VALUE;
        }
    }

    divideHelper(temp1, temp2);

    if (dividend < 0 && divisor < 0){
        return count-1;
    }

    if (dividend < 0 || divisor < 0){
        return -(count - 1);
    }

    return count-1;

}

public int divideHelper (int dividend1, int divisor1){
    if (dividend1 < 0) {
        return dividend1;
    }

    if (dividend1 >= 0) {
        dividend1 -= divisor1;
        count++;
    }

    divideHelper(dividend1, divisor1);
    return count;
}
}
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
PotatoMan
  • 71
  • 6

1 Answers1

0

This is a problem with highly-recursive code; for each nested call, java creates another "stack frame", which contains information about local variables, the active class, where to return to when the current method succeeds, etc. Threads, by default, have about 256K-1MB worth of stack that they can fill with frames; once you've recurred deeply enough, it can't fit the information about where to return to onto the stack, and you get a "Stack Overflow".

Looking at your code, I'd say that if divident/divisor is more than maybe 10,000-100,000, you're going to fill up your stack and crash. Some problems are better solved iteratively!

Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44