How to multiply by adding

Does anyone have an idea how to multiply two integers using addition in Java? For example: for i = 4 and g = 5, the code should add 4 + 4 + 4 + 4 + 4 or 5 + 5 + 5 + 5.

It is probably very simple, but I sit for hours and still can not understand the way out. Thanks in advance!

Edit: forgot to mention, this should be done by recursion!

-4
source share
5 answers
int i = 4;
int g = 5;

int total = 0;

for (int inc = 0; inc < i; inc++) {
  total += g;
}
+2
source

This should work:

public static void main(String[] args) {
    int a = -4, b = 5;
    int product = a * b;
    int ans = add(a, b);

    if (ans == product) {
        System.out.println("Answer " + ans + " is correct.");
    } else {
        System.err.println("Answer " + ans + " is NOT correct. Correct is: " + product);
    }
}

/*
 * Sum of g "copies" of i.
 * E.g. add(3, 5) = 3 + 3 + 3 + 3 + 3
 */
public static int add(int i, int g) {
    // A little optimization. 0 * any number = 0
    if (i == 0 || g == 0) {
        return 0;
    }

    if (g < 0) {
        return add(-i, -g);
    }

    // Since we use recursion we need a base case.
    if (g == 1) {
        return i;
    }

    // Define our problem in terms of the same problem, but of smaller size. 
    return i + add(i, g - 1);
}
+2
source

, , , :

public static int multiply(int a, int b) {
    if (a == 0 || b == 0)
        return 0;
    if (a == 1)
        return b;
    if (b == 1)
        return a;
    if (a < 0 && b < 0)
        return multiply(a * -1, b * -1);
    if (a < 0)
        return -1 * multiply(a * -1, b);
    if (b < 0)
        return -1 * multiply(a, b * -1);
    return a + multiply(a, b - 1);
}
+1

...

5 * 4

int result=0;
int n=5;
int m=4;

for (int i=0; i<m; i++)
{
  result+=n;
}

m n .

... ...

/**
 * Method 1, the one you call.
 * NOTE: just here to catch 0*n cases
 */
int multiply(int n, int m)
{
   if (n > 0 && m > 0)
     return rec_multiply(n,m);
   else
     return 0;
}

/**
 * Method 2, one that does all the work by 
 * calling itself over and over till the 
 * correct number of additions have been done
 */
int rec_multiply(int n, int m)
{
  return (m==0 ? 0 : multiply(n, m-1))) + n;
}

which calls itself mtime, adding neach time. The recursion must keep track of the exit condition or may cause serious problems of an infinite loop. An additional method is to catch 0 entries, and 0 * - 0.

In recursion, you call a method with n = 5, m = 4. It calls itself, each time decreasing the second number by 1. If it reaches 0, it simply returns 5, otherwise it returns another call to itself +5.

0
source

Something else that would make your teacher happy wrote a test, for example the following:

int i = 4;
int g = 5;

int answer = yourMethod(i, g);
int check = i*g;

assert answer == check;
0
source

Source: https://habr.com/ru/post/1686198/


All Articles