public static int multiply2(int num1, int num2) {
    if (num1 == 0 || num2 == 0) {
        return 0;
    }
    else {
        return num1 + multiply2(num1, num2 - 1);
    }
}
I just realized that it would be fun to make a program that could determine the product of two numbers, one or both being negative. I want to do it using recursive multiplication (basically repeated addition). Could some one help me out? Thanks!
You would test if it's 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);
    }
}
if (num1 == 0 || num2 == 0) {
        return 0;
}
else if( num2 < 0 ) {
    return - num1 + multiply2(num1, num2 + 1);
}
else {
    return num1 + multiply2(num1, num2 - 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With