java – How do I do recursive multiplication when one or both of the factors is/are negative?

java – How do I do recursive multiplication when one or both of the factors is/are negative?

if (num1 == 0 || num2 == 0) {
        return 0;
}

else if( num2 < 0 ) {
    return - num1 + multiply2(num1, num2 + 1);
}

else {
    return num1 + multiply2(num1, num2 - 1);
}
else if (num1 < 0 || num2 < 0) {
    int signum1 = num1 < 0 ? -1 : 1;
    int signum2 = num2 < 0 ? -1 : 1;
    return signum1 * signum2 * multiply(signum1 * num1, signum2 * num2);
} else {

Something like that

Note: there is a signum function and Math.abs can be used for signum * num

java – How do I do recursive multiplication when one or both of the factors is/are negative?

You would test if its negative and subtract instead of add:

public static int multiply2(int num1, int num2) {
    if (num1 == 0 || num2 == 0) {
        return 0;
    }
    else if(num2 > 0){
        return num1 + multiply2(num1, num2 - 1);
    }
    else{
        return -num1 + multiply2(num1, num2 + 1);
    }
}

Leave a Reply

Your email address will not be published.