Recursive multiplication | Recursion series
Вставка
- Опубліковано 15 лип 2024
- Exploring multiplication tackles implementing multiplication recursively without the use of the multiplication operator or loops.
Video slides:
github.com/williamfiset/algor...
0:00 Intro
0:41 The multiplication problem
1:13 Understanding multiplication
3:19 Multiplication pseudocode
5:58 Challenge
6:46 Multiplication full solution
Refreshing to see William return to youtube and creating new content. 👏
I won the challenge🎉🎉🎉
def mul(a,b):
if (a == 0):
return 0
elif (a < 0):
return mul(a+1,b) - b
else:
return mul(a-1,b) + b
Ngl William that intro was 🔥
It would be nice to gradually transition from recursion lessons to dynamic programming since recursion is a fundamental concept to understand in order to grasp DP =)
Indeed! The eventual goal would be to bridge this mini series with some of the dp videos that are already out :)
@@WilliamFiset-videos it would be really nice . waiting the the upcoming videos
Thank you)
int mul(int a , int b ) {
if (a == 0) {
return 0 ;
}
else if (a > 0) {
return mul(a - 1, b) + b;
} else {
return mul(a + 1, b) - b;
}
}
def multiply(a, b):
if b == 0:
return 0
return a + multiply(a, b-1)
print(multiply(5,5))
def multiply(a, b, c=0):
if c == b:
return 0
return a + multiply(a, b, c+1)
print(multiply(5,5))
def mul(a,b):
if a == 0:
return 0
if a < 0:
return mul(a+1, b) - b
return mul(a-1, b) + b
print(mul(-5,-5))
what if we compare a and b. if(a
what do u think?
int multiplication_negative(int a, int b)
{
if (b < 0)
{
swap(a, b);
if (b < 0)
{
b *= -1;
a *= -1;
}
}
if (!b)
return 0;
return a + multiplication_negative(a, b - 1);
}
if one of a and b is negative then swap the value and if both negative then simple treat them as positive
Might be good to compare the size of the args against each other as well.
4 * 3 => 3+3+3+3
3 * 4 => 4+4+4
Second case we save one plus instruction. For bigger numbers it makes even more sense.
That's a good point. Imagine something like mul(3, 10000) you might end up having to add up a bunch of 3s rather than a couple 10000s.
At 6:46 what if b is negative and a is +ve
In that case, the `return mul(a-1, b) + b` branch will be taken and the product will be negative since adding negative numbers together yields a negative result
If a is negative then ?
@@mkr28nv -a * -b == a * b