Why does this Java solution give zero division error?


#1
public class Solution {
    public int uniquePaths(int A, int B) {
        long res = 0;
        //(A+B-2) C (A-1)
        long num = 1;
        long den1 = 1;
        long den2 = 1;
        for(long i =2; i<A+B-1; i++) num *= i;
        for(long i =2; i<A; i++) den1 *= i;
        for(long i =2; i<B; i++) den2 *= i;
        //if (den1*den2 == 0L) throw new ArithmeticException();
        den1 *= den2;
        res = num/den1;
        return (int)res;
    }
}

regardless of if I throw the exception, it always shows the error. Also, I think that den1 can never be zero. I don’t understand what the exact problem is.


#2

Most probably due to overflows. Check this out : https://community.wegalvanize.com/s/article/Division-by-zero-or-numeric-overflow-1467234921413?language=en_US