Seems you haven't payed any mind to the requested feedback though. I really just shouldn't, but...
Your algorithm is quite literally the
definition of multiplication:
The as such most obvious implementation is
Code: Select all
for (result = 0; b > 0; b--)
result += a;
or with the tiny optimization of starting at
result = a
instead, your algorithm (although written a bit more C-like),
Code: Select all
for (result = a; b > 1; b--)
result += a
In the video you say to still not know what to do with negative numbers. As dave commented, you can simply invert both
b
and the result in that case, since
a * b = -(a * (-b))
. As I then added, also
a * b = (-a) * (-b)
, i.e.,
Code: Select all
if (b < 0) {
a = -a;
b = -b;
}
for (result = a; b > 1; b--)
result += a
Even with that taken care of this is still however the most basic algorithm possible: if b is say 4 billion you loop 4 billion (minus one...) times to arrive at the answer. If you look at the above bit-shifting one, if b is 4 billion (a 32-bit number) that one loops 32 times -- which is rather significantly less than 4 billion. Flemur added that also
a * b = exp(log(a) + log(b))
.
Those latter two do need some understanding of binary respectively general mathematics so, sure and all, but this comment still got a bit unavoidable when you said to still not know what do with negative numbers. I.e., why did you ask for feedback?