3 ms·
My favorite recursion example is multiplication. Multiplying two numbers is inherently recursive, even though we don't typically think of it that way. (Followin
by dreamcompiler 4y ago
My favorite recursion example is multiplication. Multiplying two numbers is inherently recursive, even though we don't typically think of it that way. (Following is expressed in base 10 for clarity, but in base 2, the multiplications by powers of 10 are of course merely shifts so they don't cost anything.)
68628933
* 26973931
=
(6862 * 3931) * 10000
+ (2697 * 8933) * 10000
+ (6862 * 2697) * 10000 * 10000
+ (8933 * 3931)
And then we notice that (6862 * 3931) can be expressed as
(68 * 31) * 100
+ (39 * 62) * 100
+ (68 * 39) * 100 * 100
+ (62 * 31)
and so on for the 3 remaining products. And then each of these two-digit multiplications can in principle be subdivided into 4 1-digit multiplications.
The reason the algorithm is recursive is that we're really talking about polynomial multiplication, which is convolution. (Other kinds of multiplication (e.g. dot products) are not convolution and this discussion doesn't apply to them.)
The above is interesting and curious, but is it useful? Yes. Karatsuba multiplication [0] exploits this recursion and adds some clever algebra to reduce the total number of multiplication instructions needed and thus speed up bignum multiplication.
For even bigger numbers, the Schönhage–Strassen algorithm [1] goes even further and uses the Fourier transform to convert the overarching convolution operation to element-by-element (dot-product style) multiplication.
[0] https://en.wikipedia.org/wiki/Karatsuba_algorithm#Recursive_application https://en.wikipedia.org/wiki/Karatsuba_algorithm#Recursive_...
[1] https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strasse...
- dreamcompiler 4y agoExercise: Based on the above discussion, why should squaring an n-digit number be faster than multiplying 2 different n-digit numbers?
- edflsafoiewq 4y agoEven the basic schoolbook algorithms are recursive a * (10*b + c) = 10*(a*b) + (a*c) In fact the usual method is even non-tail recursive, you build up a (literal!) stack of intermediate results which you sum back up at the end.
- contravariant 4y agoI think most schoolbook algorithms are tail recursive. They're a bit hard to write down otherwise.
- lupire 4y agoThe usual method is iterative: for digit in a, for digit in b, multiply digits and offset by sum of indices of digits. The sun results.
- Someone 4y agoA simpler way multiplication is recursive is the way it is defined for natural numbers in mathematics: a × b = 0 if b = 0 a × b = a + a × (b - 1) if b ≠ 0
- nonsapreiche 4y agoa x b = a if b = 1
- ethanwillis 4y agoWhat is a + a x 0? :)