Repeating strings efficiently
Recently, Michael Ficarra pointed me to an efficient algorithm for repeating a string several times. In this blog post, I explain how it works. The algorithm makes use of the fact that natural numbers (non-negative integers) can be represented as sums of powers of two. Natural numbers as sums of powers of two You can express any natural number as a sum of powers of two. In fact, that’s what a number in binary notation is. The value of a sequence of n binary digits d i d n-1 d n-2 ... d 0 is the sum ∑ 0 ≤ i < n d i × 2 i = d 0 × 1 + d 1 × 2 + d 2 × 4 + ... Each digit d i is either one or zero. Therefore, each addend is either a power of two or it is zero. The algorithm Roughly, the algorithm iterates over the digits starting with d 0 . After each iteration, it doubles str , the string to repeat. If the current digit is one then the current value of str is added to the result. In other words, if the digit d i is one, 2 i times str is added to the result. The ...