Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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!

like image 860
hologram Avatar asked Oct 05 '12 07:10

hologram


2 Answers

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);
    }
}
like image 191
CrazyCasta Avatar answered Nov 15 '22 12:11

CrazyCasta


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

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

else {
    return num1 + multiply2(num1, num2 - 1);
}
like image 42
Dawood ibn Kareem Avatar answered Nov 15 '22 13:11

Dawood ibn Kareem