The solution to the forehead is quite trivial, but even here the presence of a rake must be taken into account:
private int mult_step(int summand, int steps_count){ if (steps_count > 0) return summand + mult(summand, steps_count - 1); else return 0; } public int mult(int a, int b){ int summand, steps_count; Boolean negate; if(a > b){ summand = a; steps_count = Math.abs(b); negate = (b < 0); } else{ summand = b; steps_count = Math.abs(a); negate = (a < 0); } int sum = mult_step(summand, steps_count); return negate ? -sum : sum; }
That is, first we go down into the chain of b elements, and then we begin to rise back, accumulating the amount.
Let me explain what kind of rake was discussed:
Multipliers can be negative. If this is not taken into account, there will be endless recursion.
For large b, the chain will be longer than the stack can accommodate. Therefore, as the length of the chain must take the smallest of the factors.