<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tigran Hayrapetyan on Medium]]></title>
        <description><![CDATA[Stories by Tigran Hayrapetyan on Medium]]></description>
        <link>https://medium.com/@tigran.cs?source=rss-36e8a35f28b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-GNYiqMZ3JYVRo1xhv3JWw.jpeg</url>
            <title>Stories by Tigran Hayrapetyan on Medium</title>
            <link>https://medium.com/@tigran.cs?source=rss-36e8a35f28b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:28:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tigran.cs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A new insight into the Countable vs. Uncountable problem]]></title>
            <link>https://medium.com/@tigran.cs/a-new-insight-into-the-countable-vs-uncountable-problem-5072f6c7e624?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5072f6c7e624</guid>
            <category><![CDATA[countability]]></category>
            <category><![CDATA[cardinalities]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[infinity]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 14:03:08 GMT</pubDate>
            <atom:updated>2026-09-04T14:20:59.543Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Perhaps the two types of infinities can be treated as equal?</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQjc52ajaTvzRnGXVbwCsw.png" /></figure><p>The subtitle of this story looks controversial, as we have the well-known Cantor’s diagonal argument, which states the exact opposite. However, to fully appreciate the points of view presented here, I kindly request that you read the content without jumping ahead.</p><p>This story is organized in the following way:</p><ul><li>In chapter 1, we will recall countable and uncountable infinities, as well as Cantor’s Diagonal Argument (CDA), which proves that the sizes of a countable and an uncountable infinite sets are not equal.</li><li>In chapter 2, I will present the “limited case” of Cantor’s argument (when the sequences being mapped to natural numbers are limited), and we will see that the same logic is just not applicable there.</li><li>In chapter 3, we will observe several different infinite sets, to highlight an important fact that if two sequences both tend to infinity, it doesn’t make them equal by value.</li><li>In chapter 4, I will describe my vision on the possible “weak side” of Cantor’s diagonal argument.</li><li>Chapter 5 will bring together all the statements made before, and we will construct a one-to-one mapping between all elements of a countable infinite set (natural numbers) and all elements of an uncountable one (infinite binary strings).</li><li>Finally, in chapter 6, we will extend the constructed one-to-one mapping in another direction, which will highlight the “weak side” of Cantor’s diagonal argument, presented earlier.</li></ul><p>In my previous writing [KN], I defined “known real numbers” as those that can be somehow explained (either through a formula or through a concept), and have shown that such real numbers are actually countable. That also led to a philosophical question about the existence of “not known real numbers”. In this story, I attempt to go beyond and show that all real numbers are countable.</p><h3>1. Recalling Cantor’s diagonal argument</h3><p>Since the year 1874, it is known that there are two types of infinities, called “countable infinity” and “uncountable infinity”.</p><p>Countable infinity is the one where we can count all its elements. For example, the set of all fractions of the form ‘1 / <em>p</em>’, where ‘<em>p </em>∈ <em>N</em>’ is a natural number, is countable, because we can provide a one-to-one correspondence between all such fractions and all the natural numbers:</p><blockquote>1 → 1,<br>2 → 1/2,<br>3 → 1/3,<br>4 → 1/4,<br>5 → 1/5,<br>…</blockquote><p>One more example, the set of all <em>k</em>-ary roots of ‘2’, is also a countable infinity, because of the existence of the following correspondence:</p><blockquote>1 → 2<br>2 → √2<br>3 → 3√2<br>4 → 4√2<br>5 → 5√2<br>…</blockquote><p>Besides that, there also exist “uncountable” infinite sets, which, in contrast to the countable ones, can’t be counted. One example is the set of all real numbers in the half-open range [0,1). Such a set will include the numbers:</p><blockquote>1/2, 1/3, 1/4, π/4, e/16, √2/2, 1/√π, 1/√√π, …</blockquote><p>Another example of uncountable infinity is a set of all possible infinite sequences of 0s and 1s. Such a set can start with sequences that have the following prefixes:</p><blockquote>010101010101…<br>111011101110…<br>101101011001…<br>001100110011…<br>…</blockquote><p>By the way, I would like to point out here that these two presented uncountable sets are equal in size, because we can establish a one-to-one correspondence between all their elements. In such cases, it is said that they belong to the same type of infinity. We can make it because for every infinite sequence of 0s and 1s, if we put “0.” in front of it, we will get value of a real number in half-opened range [0,1), written in binary positional numeral system (where only 2 digits — ‘0’ and ‘1’ are used, instead of ordinary 10 digits of decimal numeral system). So it will look like this:</p><blockquote>0.010101010101… = 1/3<br>0.111011101110… = 14/15<br>0.101101011001… ≈ 0.709228…<br>0.001100110011… = 1/5</blockquote><p>For decades, a question remained open whether those two types of infinities are “equal” to each other. In other words, is it possible to make an unambiguous one-to-one mapping between all elements of a countable infinite set and those of an uncountable infinite set? In 1891, mathematician Georg Cantor published a paper introducing his argument, later known as “Cantor’s diagonal argument” (CDA), which stated that <strong>those two types of infinities are not equal</strong>.</p><p>The proof is quite simple. There is an excellent animation of it on [VerAnim]. Anyway, let me describe the proof here too.</p><p>Suppose we somehow managed to construct a one-to-one mapping between all natural numbers (which is by definition a countable infinity) and all possible infinite sequences of 0s and 1s (which is by definition an uncountable infinity). Let’s write it down, at least, let’s write down the top-left fragment of such correspondence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwoFZdp_1cGCNrQhjVQFkA.png" /><figcaption><em>The top-left fragment of a one-to-one correspondence between all natural numbers (n) and all infinite series of 0s and 1s (Binary string).</em></figcaption></figure><p>Here, the infinite binary sequences (also called later as “infinite binary strings” or “binary strings”) are arranged in rows, under the column “Binary string”, and the natural numbers (also called later as “keys”) are listed from top to bottom, under the column “<em>n</em>”. The table expands infinitely in both the right and down directions.</p><p>Now let’s take the digits that appear on the diagonal of the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjTB9Qm5JFSd-vvGWWOmNQ.png" /><figcaption><em>Taking the digits that appear on the diagonal of the one-to-one mapping.</em></figcaption></figure><p>Note that the diagonal itself will also be another infinite binary sequence.</p><p>Next, let’s invert the diagonal — flip all its 0s to 1s and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRN45xSkkyQXIHHCcJrN4A.png" /><figcaption><em>Inverting all the digits (red) of the infinite sequence, taken from the diagonal of the table. This results in some other (blue) infinite binary sequence.</em></figcaption></figure><p>By definition, our table contains every possible infinite binary string, so it should also contain the inverted diagonal, at some row ‘<em>k</em>’.</p><p>Cantor’s diagonal argument states that it will be impossible to find the content of the inverted diagonal on any row ‘<em>k’</em> of the table, because if, let’s say, we managed to find it on some row ‘<em>k</em>’, then the <em>k</em>-th symbol of it will geometrically overlap with the <em>k</em>-th symbol of the diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iU0DDzaPRBL1IVoNja-Ug.png" /><figcaption><em>Trying to find the inverted diagonal in the table at some row ‘k’ leads to a contradiction. The k-th digit of it is unclear.</em></figcaption></figure><p>But the inverted diagonal has all its digits flipped, so if its <em>k</em>-th digit is ‘1’, it means that the <em>k</em>-th digit of the original diagonal was ‘0’. Now, ‘0’ and ‘1’ can’t both be present in the same cell of a table. The same refers to the case when the <em>k</em>-th digit of the inverted diagonal is ‘0’.</p><p>So, our assumption that the inverted diagonal can be found at some row ‘<em>k</em>’ was wrong. This means that the inverted diagonal becomes such an infinite sequence, which will be absent in the entire table. Thus, our initial assumption that we have listed all possible infinite binary strings there turns out to be wrong. This means that it is impossible to make any one-to-one mapping between an uncountable infinite set and a countable one.</p><p>This is the proof of Cantor’s diagonal argument. It makes clear that the uncountable infinities are sort of “much larger” than the countable ones. In some sense, natural numbers will “not be enough” to count all elements of an uncountable infinity.</p><h3>2. The limited case of Cantor’s diagonal argument</h3><p>Let’s consider that we are working not with infinite binary strings, but with finite ones. If so, we will be able to precisely write down all such strings. For example, if the strings are of length “<em>L</em>=3”, then we might get the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJOSY60Lx5LD--8wzJvSig.png" /><figcaption><em>An example one-to-one mapping between all possible binary strings of length “L=3”, and integers from the range n∈[0,8).</em></figcaption></figure><p>Note, strings are written here in alphanumeric order. Also, for ease of formulas that will come later, from here on, I will draw the numbering of the left column starting from “<em>n</em>=0”.</p><p>The reason I want us to consider the finite strings case is to show that the principle of CDA will just not work here. Roughly speaking, that is because in the limited case, the table is not square-shaped, but a rectangular one. And if we search for the content of the inverted diagonal, we will actually find it. It will be found beneath the top-square region:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jfl9nfRJeecebcAjvRsOcw.png" /><figcaption><em>The diagonal in this table is “000” (marked up with purple). The inverted diagonal becomes “111” (marked up with orange), and it is found at row “k=7”.</em></figcaption></figure><p>Here we have “000” on the diagonal, which after inversion becomes “111”, and now the inverted binary string can be found down below, at the row “<em>k</em>=7”.</p><p>Let me show just one more example in this regard, to highlight that the inverted diagonal should not always be found at the very bottom. We can now take finite binary strings with length equal to “<em>L</em>=4”, and write them all down not in alphanumeric order, but by Gray code [Gray]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YcWR_qjNG2FTFSXmlXKNQ.png" /><figcaption><em>A one-to-one mapping between all possible binary strings of length “L=4”, and integers from the range n∈[0,16). The diagonal in this table is “0010” (marked up in purple). The inverted diagonal becomes “1101” (marked up with orange), and is found at row “k=9”.</em></figcaption></figure><p>Here, the diagonal will have “0010”, which, after inversion, results in “1101”. Following the principle of CDA, it can’t be found in the first 4 rows, but we can easily find it beneath, at the position “<em>k</em>=9”.</p><p>So, concluding this chapter, my purpose here was to show that for the case of finite binary strings:</p><ul><li>the table becomes a tall rectangle, and not a square,</li><li>when making strings longer, the table expands down exponentially faster than it expands to the right (because, when a single column is added, the number of rows is doubled),</li><li>the content of the inverted diagonal will always be found in such a finite table,</li><li>and it will be found below the top-square region.</li></ul><p>In some sense, when making strings longer, the row at which the inverted diagonal will be found (the orange row) will be moving down much faster, compared to the increase of the diagonal’s length (the purple cells). So the distance between them also tends to increase exponentially, with every increment of ‘<em>L</em>’. With all that, we get an impression that the purple diagonal and the orange horizontal “will actually never touch each other”, and the contradiction highlighted by CDA is absent if the strings are limited.</p><h3>3. Different infinities</h3><p>In the Encyclopedia Britannica, the word “infinity” is defined as:</p><blockquote><strong>Infinity</strong>, the concept of something that is unlimited, endless, without bound.</blockquote><p>In this chapter, I want to highlight the fact that if two sequences have no bound, thus both tend to infinity, it doesn’t make them equal in all senses. Furthermore, looking from a certain perspective, we can discover infinitely many different infinities.</p><p>As a trivial example, consider the following 3 infinite arithmetical progressions:</p><blockquote>a[i] = 2*i : A = { 0, 2, 4, 6, 8, … }<br>b[i] = 3*i : B = { 0, 3, 6, 9, 12, 15, … }<br>c[i] = 7*i : C = { 0, 7, 14, 21, 28, 35, … }</blockquote><p>Given a certain limit ‘<em>m</em>’, with the increase of index ‘<em>i</em>’, all 3 progressions will eventually cross that limit, regardless of how large ‘<em>m</em>’ is. But that fact doesn’t make these 3 progressions identical in all senses. They are still composed of different values. Certain numbers will be present in the sequence ‘<em>A</em>’, but will be missing in ‘<em>B</em>’ or ‘<em>C</em>’ (for example, <em>a</em>[<em>i</em>]=104 or <em>a</em>[<em>i</em>]=200). There are other numbers present in sequences ‘<em>A</em>’ and ‘<em>C</em>’, but absent in sequence ‘<em>B</em>’ (for example, <em>c</em>[<em>j</em>]=350 or <em>c</em>[<em>j</em>]=1400).</p><p>Another example is a binary tree [BinTree], which expands infinitely down by all its branches. Let’s label all its nodes top-down, writing the labels on each level from left to right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gaCl3z6YuIO6JKdfwO440A.png" /><figcaption><em>Labeling all the nodes of an infinite binary tree.</em></figcaption></figure><p>When walking down the tree from the root, there are infinite possible paths that we can take, because on every step we have 2 options: going into the left subtree, or going into the right one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1AsQSIqBt8vHW75ynZKyg.png" /><figcaption><em>Illustration of the first steps of 3 different paths (purple, magenta, and red) that can be taken when walking down the tree.</em></figcaption></figure><p>Note, regardless of the path that we will walk down, the numbers that we will meet on our way will tend to positive infinity, because any <em>k</em>-th level of the tree has labels in the range [ 2^k .. 2^(k+1) ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhST3vi5zhNrIMv3CUQhZA.png" /><figcaption><em>The ranges of labels of the first 4 levels of such an infinite binary tree.</em></figcaption></figure><p>The point of this example is to show that once two such paths fork from each other and continue down by different branches, they will no longer meet any common label on their way. That is, even though the labels on both paths will tend to infinity.</p><p>So, when speaking about infinite values, we should keep in mind that there are different infinities, even such ones that have no common value at all. Defining “infinity” as something which sooner or later will cross any predefined limit ‘<em>m</em>’ is far from enough if we want to describe the pattern of those values.</p><p>The concept of having two infinite values, which are not equal to each other, can be linked to the theory of <em>p</em>-adic numbers [P]. Any <em>p</em>-adic number is an infinite integer, if interpreted from the traditional point of view. At the same time, they are represented as infinite series of digits in <em>p</em>-ary positional numeral system, which already allows two <em>p</em>-adic numbers to be not equal by value. Ordinary operations such as addition and multiplication are also defined for <em>p</em>-adics.</p><h3><em>4. The possible “weak side” in Cantor’s diagonal argument</em></h3><p>Recalling Cantor’s diagonal argument (CDA) from chapter 1, we can write down the following 4 points:</p><blockquote><strong>1</strong> — In the produced table of infinite binary strings, we have the diagonal, which goes infinitely in the right-down direction,<br><strong>2</strong> — We can invert the content of that diagonal,<br><strong>3</strong> — There should be some row ‘k’ which will have the content of the inverted diagonal,<br><strong>4</strong> — There is the intersection of that row ‘k’ and the diagonal, at cell (k,k), the value of which causes the contradiction.</blockquote><p>Upon me, the possible “weak side” resides in the 3rd point, where we mention ‘<em>k</em>’ as some finite index of a row, while in fact that index is infinite.</p><p>When trying to construct a one-to-one correspondence between infinite binary strings and natural numbers, every infinite binary string requires an infinitely long description. At the same time, every natural number can be described in a finite number of steps, as it is composed of finite decimal digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxQkEp1SU-RmIzHhVfCz8Q.png" /></figure><p>If we think that we can find a finite index of the inverted diagonal, then we should also assume that we can do the same for any other infinite binary string. So, given any infinite binary string, there should be a way to provide a finite index in the table, where that string will reside. Continuing like that, any finite set of infinite binary strings can then be matched with some finite set of finite indices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHUttA4Q9vCpxJDBfgxpGQ.png" /><figcaption><em>Example of one-to-one matching between some infinite binary strings and some finite integers.</em></figcaption></figure><p>Such an assumption becomes contradictory from the viewpoint of the Theory of Information. A finite set of infinite binary strings by itself contains an infinite amount of information. While a finite set of finite indices contains a finite amount of information. Thus, what we are trying to do is to have a one-to-one mapping between some set of infinite information and some other set of finite one. Obviously, that is not possible.</p><p>So, to not find ourselves in the mentioned contradiction, when speaking about indices of arbitrary infinite binary strings, we should also allow for those indices to be infinite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7lzliCQl5y4m2opKAqtTA.png" /><figcaption><em>Example of one-to-one matching between some infinite binary strings and some infinite integers.</em></figcaption></figure><p>I guess the reason why Cantor’s diagonal argument looks so obvious to us is that we try to perceive it visually. We imagine in our minds the beginning of the diagonal, then we imagine the beginning of some row ‘<em>k</em>’, and that allows us to visually imagine the cell of their intersection (<em>k</em>,<em>k</em>). The purpose of this chapter was to show that we can’t imagine it all like that, because ‘<em>k</em>’ can also be an infinite index.</p><h3><em>5. Building a one-to-one mapping between all natural numbers and all infinite binary strings</em></h3><p>After all the theoretical assumptions presented above, let’s do the practice and construct a one-to-one mapping between “countable” and “uncountable” infinities.</p><p>This time, we will fill the content of the table not from top to bottom, but from left to right. So instead of writing the first infinite binary string till the end, then the second one, and so on, we will write the first digits of all binary strings, then their second digits, and so on.</p><p>As a binary string might start both from 0 and 1, let’s be “prepared” for both cases and write 0 and 1 in an interleaved way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0SxaXBLLnyh97bdiyMIzA.png" /><figcaption><em>The first digits of all infinite binary strings. The periodicity here is 2 rows.</em></figcaption></figure><p>Next, regardless of the value of the first digit, as the second digit can also be 0 or 1, we will write them also interleaved, but now with a periodicity of 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVxQsaK7juWErMcta6TDUA.png" /><figcaption><em>The first and second digits of all infinite binary strings. The periodicity becomes 4 rows.</em></figcaption></figure><p>This way, we will keep ourselves “prepared” for any 2-long prefix of a binary string, while not making the mapping dense around any index ‘<em>n</em>’.</p><p>Regardless of the 1st and 2nd digits, the 3rd digit can also be 0 or 1; that’s why we will write it down, with periodicity of 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECKDbDqgxFcIUVzjvVK1bQ.png" /><figcaption><em>First three digits of all infinite binary strings. The periodicity becomes 8 rows.</em></figcaption></figure><p>Let’s agree, now we are ready for any 3-long prefix of an infinite binary string, and we are not making the mapping dense or sparse around any index.</p><p>We already see the pattern. If numbering digits of the binary strings starting from 0, then when filling the <em>k</em>-th column of digits, we will start with ‘0’s and keep flipping with periodicity 2^<em>k</em>. In that way, any <em>k</em>-long prefix of an infinite binary string can be found in the first 2^<em>k</em> strings, as well as in the next 2^<em>k</em> strings, or the next 2^<em>k</em> strings coming after them, and so on…</p><p>We can even give an exact formula/algorithm for obtaining the binary string from a given key, and vice versa. To obtain the key from an infinite binary string, the algorithm is:</p><pre>function stringToKey( series: BinaryString ) --&gt; Integer<br>   key := 0<br>   for i := 0 to +∞<br>      if series[i] == 1<br>         key := key + 2^i<br>   return key</pre><p>And to do the reverse calculation:</p><pre>function keyToString( key: Integer ) --&gt; BinaryString<br>   series := &quot;&quot;  // Empty binary string<br>   for i := 0 to +∞<br>      append &#39;key mod 2&#39; to &#39;series&#39;<br>      key := ⌊key / 2⌋<br>   return series</pre><p>Careful readers might notice that the produced binary strings are the same keys taken from the left side of the table, but written in binary notation, with their digits being written from right to left.</p><p>This mapping between “countable” and “uncountable” infinities also has the property that ‘<em>key</em>’ will be a finite integer if and only if its string has a finite count of ‘1’s. Otherwise, the ‘<em>key</em>’ will be infinite. And that is why I wrote Chapter 3 about different infinities, to show that if two different binary strings both have an infinite amount of ‘1’s, so their keys are both infinite, that will not make those keys equal to each other.</p><p>For example, here are two strings with repeating patterns:</p><blockquote>s1=’01010101…’ (the pattern is ‘01’),<br>s2=’001001001…’ (the pattern is ‘001’),</blockquote><p>With the help of <em>stringToKey</em>() function presented above, we obtain their keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQx6JdUpVPJXb2eCXHMKcg.png" /></figure><p>The produced ‘<em>key</em>1’ and ‘<em>key</em>2’ are both infinite, but have different values.</p><p>On the other hand, having an infinite binary string, if we address only its <em>L</em>-long finite prefix, we will be able to navigate to a finite index in the range “[0, 2^<em>L</em>)” in our table, where a string with such a prefix will be found. So the information preservation principle remains.</p><p>I want to conclude this chapter in the form of <em>Q</em>&amp;<em>A</em>, with some possible arguments against the presented points:</p><blockquote><strong>Q</strong>. “This is not a mapping since it takes an infinite time to calculate”.</blockquote><blockquote><strong>A</strong>. Yes, it can take infinite time indeed. But how can we expect an infinite string to be converted into a natural number in a finite amount of time? If we are working with an infinite binary string, even putting all the calculations aside, only addressing every digit will already take an infinite time.</blockquote><blockquote><strong>Q</strong>. “This is not a mapping since the keys might result in infinitely large numbers”.</blockquote><blockquote><strong>A</strong>. Yes, the keys might be infinitely large indeed; in other words, they might have infinite amount of decimal digits. However, how do we expect it to be the other way? If we limit ourselves only to a finite amount of digits, then all possible keys that can be constructed with them will also be finite, and obviously, that will not be enough to map any infinite set.</blockquote><h3><em>6. Extending the table upwards</em></h3><p>Cantor’s diagonal argument operates on the content of the table’s diagonal. As we just figured out our own mapping, let’s see what the diagonal is there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRkNQwTm1AO0nLe9d_DclA.png" /><figcaption><em>In the one-to-one mapping that we just figured out, the content of the diagonal is all zeroes (blue cells), because in every column, the first ‘1’ comes later (yellow cells).</em></figcaption></figure><p>Let’s denote digit of <em>n</em>-th row and <em>j</em>-th column as <em>A</em>[<em>n</em>,<em>j</em>]. Both ’<em>n</em>’ and ‘<em>j</em>’ start from 0.</p><ul><li>We have <em>A</em>[0,0]=0 in the table,</li><li>In the second column (<em>j</em>=1), the first ‘1’ comes at cell <em>A</em>[2,1],</li><li>In the third column (<em>j</em>=2), the first ‘1’ comes at cell <em>A</em>[4,2],</li><li>And so on, in every <em>j</em>-th column the first ‘1’ comes at cell <em>A</em>[2^<em>j</em>, <em>j</em>].</li></ul><p>All that means that the diagonal in our mapping is all zeroes: “0000…”. Thus, the content of the inverted diagonal will be all ones: “1111…”.</p><p>Now, let’s try to find the row with the inverted diagonal. Upon the pseudo-code, its key should be calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uCjbF7cFhcd4sjPocjqog.png" /></figure><p>In some sense, it becomes the “maximal possible key”, as we use all possible powers of ‘2’, to sum it up. Obviously, we will not find the row with that “<em>key</em>” in the table, as the “<em>key</em>” itself turns out to be infinite. But we can find it somewhere else…</p><p>This time, let’s look at how the <em>p</em>-th infinite binary string changes when we move upwards by one row, i.e., to (<em>p</em>-1)-th string. More precisely, let’s track such adjacent rows ‘<em>p</em>’ and ‘<em>p</em>-1’, where the digit of a certain column ‘<em>j</em>’ becomes ‘1’ (i.e., “<em>A</em>[<em>p</em>][<em>j</em>] = 0”, but “<em>A</em>[<em>p</em>-1][<em>j</em>] = 1”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pruLuI149JciBgTSs1WD_A.png" /><figcaption><em>All the up-down adjacent cells, where the lower cell is 0 and the upper cell is 1. We see that in the j-th column such a transition happens once in 2^j rows</em>.</figcaption></figure><ul><li>In the first column (<em>j</em>=0), the digit becomes ‘1’ on rows “<em>p</em> = 1, 3, 5, 7, …”, or when “<em>p</em>=2*<em>i</em>+1”, where ‘<em>i</em>’ is a non-negative integer.</li><li>In the second column (<em>j</em>=1), the digit becomes ‘1’ on rows “<em>p</em> = 3, 7, 11, 15, …” or when “<em>p</em>=4*<em>i</em>+3”.</li><li>In the third column (<em>j</em>=2), the digit becomes ‘1’ on rows “<em>p</em> = 7, 15, 23, …” or when “<em>p</em>=8*<em>i</em>+7”.</li><li>And so on, in any <em>j</em>-th column, the digit becomes ‘1’ on rows “<em>p</em> = 2^(<em>j</em>+1)*<em>i</em> + (2^(<em>j</em>+1)–1)”, where ‘<em>i</em>’ is a non-negative integer.</li></ul><p>Having noted such behavior, what will happen if we extend our table upwards by one row — i.e., if we introduce the key ‘-1’? Keeping the mentioned behavior, when moving from row ‘0’ to row ‘-1’, those transitions of zeroes into ones will happen at every column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mskn1BpP3VlGlOg-wSd6rA.png" /><figcaption><em>Extending the table upwards by one row results in the new key ‘-1’ having all its digits equal to ‘1’.</em></figcaption></figure><p>As we noted right before, at any <em>j</em>-th column, the digit becomes from ‘0’ to ‘1’ on rows “<em>p</em> = 2^(<em>j</em>+1)*<em>i</em> + (2^(<em>j</em>+1)–1)”. Now, taking “<em>i</em>=-1” will result in: <br>“<em>p</em> = -2^(<em>j</em>+1) + (2^(<em>j</em>+1)–1) = -1”, meaning that when moving from row ‘0’ to row ‘-1’, all the digits will become ‘1’.</p><p>And that is the content of the inverted diagonal that we were looking for. It resides one position “upwards” from the diagonal itself, so they never touch each other; thus, the values of their cells don’t contradict. They would be touching each other only if the table is finite and cyclic, which is definitely not our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSBl9PfmZJ_YxIU710Xn6g.png" /><figcaption><em>The diagonal (blue cells) and the row with inverted diagonal (green cells) are both present in the one-to-one mapping that we have figured out, and they do not intersect.</em></figcaption></figure><p>My purpose in this chapter was to show why the diagonal and the row with its inverted content can actually have no intersection. By the way, if we try to run the logic of CDA on the latest updated table, we will see that the row with the content of the inverted new diagonal will still be found one position above.</p><h3>Conclusion</h3><p>In this story, we have looked at Cantor’s diagonal argument from different angles, inspected its limited case, and found that there can be cases without the contradiction — i.e., such cases when the diagonal and the row with inverted diagonal have no intersection. In Chapter 5, we succeeded in constructing a one-to-one mapping between all natural numbers and all infinite binary strings. If all that is true, then the countable and the uncountable infinities turn out to have equal size.</p><p>Thank you for your attention!</p><p>I am open to any kind of arguments and conversations, and I will be happy to receive any constructive critique of these results.</p><blockquote>All the used images are prepared by Asya Papyan — <a href="https://www.linkedin.com/in/asya-papyan-b0a1b0243/">https://www.linkedin.com/in/asya-papyan-b0a1b0243/</a></blockquote><blockquote>If you enjoyed reading this story, feel free to follow me on LinkedIn, where I generally write on other topics, such as Algorithms and Data Structures — <a href="http://linkedin.com/in/tigran-hayrapetyan-cs/">linkedin.com/in/tigran-hayrapetyan-cs/</a></blockquote><blockquote>All images are designed upon the request of the author.</blockquote><h3>References</h3><p>[KN] — Why all known real numbers are actually countable: <a href="https://www.cantorsparadise.com/why-all-known-real-numbers-are-actually-countable-f09e57f83f4d">https://www.cantorsparadise.com/why-all-known-real-numbers-are-actually-countable-f09e57f83f4d</a></p><p>[VerAnim] — Math’s Fundamental Flaw (by Veritasium): <a href="https://youtu.be/HeQX2HjkcNo?si=ooV_I4b_bufLUuXO&amp;t=224">https://youtu.be/HeQX2HjkcNo?si=ooV_I4b_bufLUuXO&amp;t=224</a></p><p>[Gray] — Gray code: <a href="https://en.wikipedia.org/wiki/Gray_code">https://en.wikipedia.org/wiki/Gray_code</a></p><p>[BinTree] — Binary tree: <a href="https://en.wikipedia.org/wiki/Binary_tree">https://en.wikipedia.org/wiki/Binary_tree</a></p><p>[P] — <em>p</em>-adic numbers: <a href="https://en.wikipedia.org/wiki/P-adic_number">https://en.wikipedia.org/wiki/P-adic_number</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5072f6c7e624" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cyclic Partition: An Up to 1.5x Faster Partitioning Algorithm]]></title>
            <link>https://medium.com/data-science/cyclic-partition-an-up-to-1-5x-faster-partitioning-algorithm-e38bf7948a5f?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e38bf7948a5f</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[partition]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 17:28:03 GMT</pubDate>
            <atom:updated>2026-09-04T14:35:18.839Z</atom:updated>
            <content:encoded><![CDATA[<h4>A sequence partitioning algorithm that does minimal rearrangements of values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*i2F4sw1EN4eECdYynHHOyA.png" /></figure><p>1. Introduction</p><p>Sequence partitioning is a basic and frequently used algorithm in computer programming. Given a sequence of numbers “<em>A</em>”, and some value ‘<em>p</em>’ called pivot value, the purpose of a partitioning algorithm is to rearrange numbers inside “<em>A</em>” in such a way, so that all numbers less than ‘<em>p</em>’ come first, followed by the rest of the numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*xJmOiPIqwI9mI4J_fMw-WA.png" /><figcaption><em>An example of a sequence before and after partitioning by pivot value “p=20”. <br>After the algorithm, all the values which are less than 20 (light green)<br>appear before the other values (yellow).</em></figcaption></figure><p>There are different applications of partitioning, but the most popular are:</p><ul><li>QuickSort — which is generally nothing more than a partitioning algorithm, called through recursion multiple times on different sub-arrays of given array, until it becomes sorted.</li><li>Finding the median value of a given sequence — which makes use of partitioning in order to efficiently cut down the search range, and to ultimately find the median in expected linear time.</li></ul><p>Sorting a sequence is an essential step to enable faster navigation over large amounts of data. Of the two common searching algorithms — linear search and binary search — the latter can only be used if the data in the array is sorted. Finding the median or k’th order statistic can be essential to understand the distribution of values in given unsorted data.</p><p>Currently there are different partitioning algorithms (also called — partition schemes), but the well-known ones are “Lomuto scheme” and “Hoare scheme”. Lomuto scheme is often intuitively easier to understand, while Hoare scheme does less rearrangements inside a given array, which is why it is often preferred in practice.</p><p>What I am going to suggest in this story is a new partition scheme called “cyclic partition”, which is similar to Hoare scheme, but does 1.5 times fewer rearrangements (value assignments) inside the array. Thus, as it will be shown later, the number of value assignments becomes almost equal to the number of the values which are initially “not at their place”, and should be somehow moved. That fact allows me to consider this new partition scheme as a nearly optimal one.</p><p>The next chapters are organized in the following way:</p><ul><li>In chapter 2 we will recall what is in-place partitioning (a property, which makes partitioning to be not a trivial task),</li><li>In chapter 3 we will recall the widely used Hoare partitioning scheme,</li><li>In chapter 4 I’ll present “cycles of assignments”, and we will see why some rearrangements of a sequence might require more value assignments, than other rearrangements of the same sequence,</li><li>Chapter 5 will use some properties of “cycles of assignments”, and derive the new “cyclic partition” scheme, as an optimized variant of Hoare scheme,</li><li>And finally, chapter 6 will present an experimental comparison between the Hoare scheme and cyclic partition, for arrays of small and large data types.</li></ul><p>An implementation of Cyclic partition in the C++ language, as well as its benchmarking with the currently standard Hoare scheme, are present on GitHub, and are referenced at the end of this story [1].</p><h3>2. Recalling in-place sequence partitioning</h3><p>Partitioning a sequence will not be a difficult task, if the input and output sequences would reside in computer memory in 2 different arrays. If that would be the case, then one of methods might be to:</p><ol><li>Calculate how many values in “<em>A</em>” are less than ‘<em>p</em>’ (this will give us final length of the left part of output sequence),</li><li>Scan the input array “<em>A</em>” from left to right, and append every current value “<em>A</em>[<em>i</em>]” either to the left part or to the right part, depending on whether it is less than ‘<em>p</em>’ or not.</li></ol><p>Here are presented a few states of running such algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ono-le72len_2TIezMbtJA.png" /><figcaption><em>During the first stage we calculate that there are only 7 values less than “p=20” (the light green ones), so we prepare to write the greater values into the output sequence, starting from index 7.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*T7SkpVOEr1wbnLusr0j-kg.png" /><figcaption><em>During the second stage, after scanning 5 values of the input sequence, <br>we append 3 of them to the left part of output sequence, <br>and the other 2 to its right part.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*lIXYk45esW2wZPOmVn49kA.png" /><figcaption><em>Continuing the second stage, we have scanned now 9 values from input sequence, <br>placing 5 of them in the left part of output sequence, and the other 4 to its right part.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*0VfqbeNf_htkb_6YzFbh-g.png" /><figcaption><em>The algorithm is completed. Both parts of the output sequence are now properly filled to the end. <br>Note, the relative order of values in either left or right parts is preserved, <br>upon how they were originally written in the input array.</em></figcaption></figure><p>Other, shorter solutions also exist, such ones which have only one loop in the code.</p><p>Now, the difficulty comes when we want to not use any extra memory, so the input sequence will be transformed into the partitioned output sequence just by moving values inside the only array. By the way, such kind of algorithms which don’t use extra memory are called in-place algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*3FH-T2llHsEVrd9_a_hwPQ.png" /><figcaption><em>Partitioning the same input sequence “A” in-place, by the same pivot value “p=20”.<br>Presented order of values corresponds to the input state of the sequence, and arrows for every value show <br>if where to that value should be moved, in order for the entire sequence to become partitioned.</em></figcaption></figure><p>Before introducing my partitioning scheme, let’s review the existing and commonly used solution of in-place partitioning.</p><h3>3. The currently used partitioning scheme</h3><p>After observing a few implementations of sorting in standard libraries of various programming languages, it looks like the most widely used partitioning algorithm is the Hoare scheme. I found out that it is used for example in:</p><ul><li>“std::sort()” implementation in STL for C++,</li><li>“Arrays.sort()” implementation in JDK for Java, for primitive data types.</li></ul><p>In the partitioning based on the Hoare scheme, we scan the sequence simultaneously from both ends towards each other, searching in the left part such a value <em>A</em>[<em>i</em>] which is greater or equal to ‘<em>p</em>’, and searching in the right part such a value <em>A</em>[<em>j</em>] which is less than ‘<em>p</em>’. Once found, we know that those two values <em>A</em>[<em>i</em>] and <em>A</em>[<em>j</em>] are kind of “not at their proper places” (remember, the partitioned sequence should have the values less than ‘<em>p</em>’ coming first, and only then all the other values which are greater or equal to ‘<em>p</em>’), so we just swap <em>A</em>[<em>i</em>] and <em>A</em>[<em>j</em>]. After the swap, we continue the same way, simultaneously scanning array “<em>A</em>” with indexes <em>i</em> and <em>j</em>, until they become equal. Once they are, partitioning is completed.</p><p>Let’s observe the Hoare scheme on another example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*CIjFf2_knUB9b0bxD2pc7A.png" /><figcaption><em>The input sequence “A” of length ’N’, that should be partitioned by pivot value “p=20”. <br>Index i starts scanning from 0 upwards, and index j starts scanning from “N-1” downwards.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*LJpR8UVVelNaE37vEo-sgA.png" /><figcaption>While increasing index i we meet value “A[2]=31” which is greater than ‘p’. Then, after decreasing index j <br>we meet another value “A[10]=16” which is less than ‘p’. Those 2 are going to be swapped.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*cGimM0p18HUb-vlSrEq47g.png" /><figcaption><em>After swapping “A[2]” and “A[10]” we continue increasing i from 2 and decreasing j from 10. Index i will stop on value “A[4]=28” which is greater than ‘p’, and index j will stop on value “A[9]=5” which is less than ‘p’. Those 2 are also going to be swapped.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*3Ec_64TPWu8psgkBDYhAaQ.png" /><figcaption><em>The algorithm continues the same way, and the numbers “A[5]=48” and “A[7]=3” are also going to be swapped.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*gW0-CPWSzpgtrlLyU1UP7Q.png" /><figcaption><em>After that, indexes ‘i’ and ‘j’ will become equal to each other. Partitioning is completed.</em></figcaption></figure><p>If writing the pseudo-code of partitioning by the Hoare scheme, we will have the following:</p><pre>// Partitions sequence A[0..N) with pivot value &#39;p&#39; <br>// upon Hoare scheme, and returns index of the first value <br>// of the resulting right part.<br>function partition_hoare( A[0..N) : Array of Integers, p: Integer ) : Integer<br>    i := 0<br>    j := N-1<br>    while true<br>        // Move left index &#39;i&#39;, as much as needed<br>        while i &lt; j and A[i] &lt; p<br>            i := i+1<br>        // Move right index &#39;j&#39;, as much as needed<br>        while i &lt; j and A[j] &gt;= p<br>            j := j-1<br>        // Check for completion<br>        if i &gt;= j<br>            if i == j and A[i] &lt; p<br>                return i+1  // &quot;A[i]&quot; also refers to left part<br>            else<br>                return i  // &quot;A[i]&quot; refers to right part<br>        // Swap &quot;A[i]&quot; and &quot;A[j]&quot;<br>        tmp := A[i]<br>        A[i] := A[j]<br>        A[j] := tmp<br>        // Advance by one both &#39;i&#39; and &#39;j&#39;<br>        i := i+1<br>        j := j-1</pre><blockquote>Here in lines 5 and 6 we set up start indexes for the 2 scans.</blockquote><blockquote>Lines 8–10 search from left for such a value, which should belong to the right part, after partitioning.</blockquote><blockquote>Similarly, lines 11–13 search from right for such a value, which should belong to the left part.</blockquote><blockquote>Lines 15–19 check for completion of the scans. Once indexes ‘i’ and ‘j’ meet, there are 2 cases: either “A[i]” belongs to the left part or to the right part. Depending on that, we return either ‘i’ or ‘i+1’, as return value of the function should be the start index of the right part.</blockquote><blockquote>Next, if the scans are not completed yet, lines 20–23 do swap those 2 values which are not at their proper places.</blockquote><blockquote>And finally, lines 24–26 advance the both indexes, in order to not re-check the already swapped values.</blockquote><p>The time complexity of the algorithm is <em>O</em>(<em>N</em>), regardless of where the 2 scans will meet each other, as together they always scan <em>N</em> values.</p><p>An important note here, if the array “<em>A</em>” has ‘<em>L</em>’ values which are “not at their places”, and should be swapped, then acting by Hoare scheme we will do “3*<em>L</em>/2” assignments, because swapping 2 values requires 3 assignments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*T3YWE_KUfGDnxZ5XX4Ydkw.png" /><figcaption><em>Swapping values of 2 variables ‘a’ and ‘b’ requires to do 3 assignments, with help of ‘tmp’ variable.</em></figcaption></figure><p>Those assignments are:</p><pre>tmp := a<br>a := b<br>b := tmp</pre><p>Let me also emphasize here that ‘<em>L</em>’ is always an even number. That is because for every value “<em>A</em>[<em>i</em>]&gt;=<em>p</em>” originally residing at the left area, there is another value “<em>A</em>[<em>j</em>]&lt;<em>p</em>” originally residing at the right area, the ones which are being swapped. So, every swap rearranges 2 such values, and all rearrangements in Hoare scheme are being done only through swaps. That’s why the ‘<em>L</em>’ — the total number of values to be rearranged, is always an even number.</p><h3>4. Cycles of assignments</h3><p>This chapter might look as a deviation from the agenda of the story, but actually it isn’t, as we will need the knowledge about cycles of assignments in the next chapter, when optimizing the Hoare partitioning scheme.</p><p>Assume that we want to somehow rearrange the order of values in given sequence “<em>A</em>”. This should not necessarily be a partitioning, but any kind of rearrangement. Let me show that some rearrangements require more assignments than some others.</p><h4>Case #1: Cyclic left-shift of a sequence</h4><p>How many assignments should be done if we want to cyclic left shift the sequence “<em>A</em>” by 1 position?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ztfpq5VXRBPunh9CfYhRdA.png" /><figcaption><em>Example of cyclic left shift of sequence “A” of length N=12. <br>We see that the number of assignments needed is N+1=13, as we need to: <br>1) store “A[0]” in the temporary variable “tmp”, then<br>2) “N-1” times assign the right adjacent value to the current one, and finally <br>3) assign “tmp” to the last value of the sequence “A[N-1]”.</em></figcaption></figure><p>The needed operations to do that are:</p><pre>tmp := A[0]<br>A[0] := A[1]<br>A[1] := A[2]<br>...<br>A[9] := A[10]<br>A[10] := A[11]<br>A[11] := tmp</pre><p>… which results in 13 assignments.</p><h4>Case #2: Cyclic left-shift by 3 positions</h4><p>In the next example we still want to do a cyclic left shift of the same sequence, but now by 3 positions to the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Xe8c5Ce85VwpMzCmZzot8g.png" /><figcaption><em>Example of cyclic left shift by 3 of the sequence “A”, having length N=12.<br>We see that the values A[0], A[3], A[6] and A[9] are being exchanged between each other (blue arrows), <br>as well as values A[1], A[4], A[7] and A[10] do (pink arrows),<br>and as the values A[2], A[5], A[8] and A[11] do exchange only between each other (yellow arrows).<br>The “tmp” variable is being assigned to and read from 3 times.</em></figcaption></figure><p>Here we have 3 independent chains / cycles of assignments, each of length 4.</p><p>In order to properly exchange values between <em>A</em>[0], <em>A</em>[3], <em>A</em>[6] and <em>A</em>[9], the needed actions are:</p><pre>tmp := A[0]<br>A[0] := A[3]<br>A[3] := A[6]<br>A[6] := A[9]<br>A[9] := tmp</pre><p>… which makes 5 assignments. Similarly, exchanging values inside groups (<em>A</em>[1], <em>A</em>[4], <em>A</em>[7], <em>A</em>[10]) and (<em>A</em>[2], <em>A</em>[5], <em>A</em>[8], <em>A</em>[11]) will require 5 assignments each. And adding all that together gives 5*3=15 assignments required to cyclic left shift by 3 the sequence “<em>A</em>”, having <em>N</em>=12 values.</p><h4><em>Case #3: Reversing a sequence</em></h4><p>When reversing the sequence “<em>A</em>” of length ’<em>N</em>’, the actions performed are:</p><ul><li>swap its first value with the last one, then</li><li>swap the second value with the second one from right,</li><li>swap the third value with the third one from right,</li><li>… and so on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*-UOhLPiDZMkTr3HUKjx6dA.png" /><figcaption><em>Example of reversing array “A”, having N=12 values.<br>We see that the values in pairs (A[0], A[11]), (A[1], A[10]), (A[2], A[9]), etc, are being swapped, independently from each other. The variable “tmp” is being assigned to and read from 6 times.</em></figcaption></figure><p>As every swap requires 3 assignments, and as for reversing entire sequence “<em>A</em>” we need to do ⌊<em>N</em>/2⌋ swaps, the total number of assignments results in:</p><blockquote>3*⌊N/2⌋ = 3*⌊12/2⌋ = 3*6 = 18</blockquote><p>And the exact sequence of assignments needed to do the reverse of “<em>A</em>” is:</p><pre>tmp := A[0]    // Cycle 1<br>A[0] := A[11]<br>A[11] := tmp<br>tmp := A[1]    // Cycle 2<br>A[1] := A[10]<br>A[10] := tmp<br><br>...<br><br>tmp := A[5]    // Cycle 6<br>A[5] := A[6]<br>A[6] := tmp</pre><h4>Summary</h4><p>We have seen that rearranging values of the same sequence “<em>A</em>” might require different number of assignments, depending on how exactly the values are being rearranged.</p><p>In the presented 3 examples, the sequence always had length of <em>N</em>=12, but the number of required assignments was different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sCaN6Wz5QHRGIQN_KTvZA.png" /></figure><p>More precisely, the number of assignments is equal to <em>N</em>+<em>C</em>, where “<em>C</em>” is the number of cycles, which originate during the rearrangement. Here by saying “cycle” I mean such a subset of variables of “<em>A</em>”, values of which are being rotated among each other.</p><p>In our case 1 (left shift by 1) we had only <em>C</em>=1 cycle of assignments, and all variables of “<em>A</em>” did participate in that cycle. That’s why overall number of assignments was:</p><blockquote>N+C = 12+1 = 13.</blockquote><p>In the case 2 (left shift by 3) we had <em>C</em>=3 cycles of assignments, with:<br> — first cycle within variables (<em>A</em>[0], <em>A</em>[3], <em>A</em>[6], <em>A</em>[9]), <br> — second cycle applied to variables (<em>A</em>[1], <em>A</em>[4], <em>A</em>[7], <em>A</em>[10]) and <br> — third cycle applied to variables (<em>A</em>[2], <em>A</em>[5], <em>A</em>[8], <em>A</em>[11]).</p><p>That’s why the overall number of assignments was:</p><blockquote>N+C = 12+3 = 15.</blockquote><p>And in our case 3 (reversing) we had ⌊<em>N</em>/2⌋ = 12/2 = 6 cycles. Those all were the shortest possible cycles, and were applied to pairs (<em>A</em>[0], <em>A</em>[11]), (<em>A</em>[1], <em>A</em>[10]), … and so on. That’s why the overall number of assignments was:</p><blockquote>N+C = 12+6 = 18.</blockquote><p>Surely, in the presented examples the absolute difference in number of assignments is very small, and it will not play any role when writing high-performance code. But that is because we were considering a very short array of length “<em>N</em>=12”. For longer arrays, those differences in numbers of assignments will grow proportionally to <em>N</em>.</p><p>Concluding this chapter, let’s keep in mind that the number of assignments needed to rearrange a sequence grows together with number of cycles, introduced by such rearrangement. And if we want to have a faster rearrangement, we should try to do it by such a scheme, which has the smallest possible number of cycles of assignments.</p><h3><strong>5. Optimizing the Hoare partitioning scheme</strong></h3><p>Now let’s observe the Hoare partitioning scheme once again, this time paying attention to how many cycles of assignments it introduces.</p><p>Let’s assume we have the same array “<em>A</em>” of length <em>N</em>, and a pivot value ‘<em>p</em>’ according to which the partitioning must be made. Also let’s assume that there are ‘<em>L</em>’ values in the array which should be somehow rearranged, in order to bring “<em>A</em>” into a partitioned state. It turns out that Hoare partitioning scheme rearranges those ‘<em>L</em>’ values in the slowest possible way, because it introduces the maximal possible number of cycles of assignments, with every cycle consisting of only 2 values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*VUZQ6-qJr-2baLSS8s5CFw.png" /><figcaption><em>Given pivot value “p=20”, the “L=8” values which should be rearranged are the ones to which <br>arrows are coming (or going from).<br>Hoare partitioning scheme introduces “L/2=4” cycles of assignments, each acting on just 2 values.</em></figcaption></figure><p>Moving 2 values over a cycle of length 2, which is essentially swapping them, requires 3 assignments. So the overall number of values assignments is “3*<em>L</em>/2” for the Hoare partitioning scheme.</p><p>The idea which lies beneath the optimization that I am going to describe, comes from the fact that after partitioning a sequence, we are generally not interested in relative order of the values “<em>A</em>[<em>i</em>]&lt;<em>p</em>”, which should finish at the left part of partitioned sequence, as well as we are not interested in the relative order of the ones, which should finish at the right part. The only thing that we are interested in, is for all values less than ‘<em>p</em>’ to come before the other ones. This fact allows us to alter the cycles of assignments in Hoare scheme, and to come up with only 1 cycle of assignments, containing all the ‘<em>L</em>’ values, which should somehow be rearranged.</p><p>Let me first describe the altered partitioning scheme with the help of the following illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*e8lkn4uR2R9y78rtK7S5wA.png" /><figcaption><em>The altered partitioning scheme, applied to the same sequence “A”.<br>As the pivot “p=20” is not changed, the “L=8” values which should be rearranged are also the same.<br>All the arrows represent the only cycle of assignments in the new scheme. <br>After moving all the ‘L’ values upon it, we will end up with an alternative partitioned sequence.</em></figcaption></figure><p>So what are we doing here?</p><ul><li>As in the original Hoare scheme, at first we scan from the left and find such value “<em>A</em>[<em>i</em>]&gt;=<em>p</em>” which should go to the right part. But instead of swapping it with some other value, we just remember it: “<em>tmp </em>:= <em>A</em>[<em>i</em>]”.</li><li>Next we scan from right and find such value “<em>A</em>[<em>j</em>]&lt;<em>p</em>” which should go to the left part. And we just do the assignment “<em>A</em>[<em>i</em>] := <em>A</em>[<em>j</em>]”, without loosing the value of “<em>A</em>[<em>i</em>]”, as it is already stored in “<em>tmp</em>”.</li><li>Next we continue the scan from left, and find such value “<em>A</em>[<em>i</em>]&gt;=<em>p</em>” which also should go to the right part. So we do the assignment “<em>A</em>[<em>j</em>] := <em>A</em>[<em>i</em>]”, without loosing value “<em>A</em>[<em>j</em>]”, as it is already assigned to the previous position of ‘<em>i</em>’.</li><li>This pattern continues, and once indexes <em>i</em> and <em>j</em> meet each other, it remains to place some value greater than ‘<em>p</em>’ to “<em>A</em>[<em>j</em>]”, we just do “<em>A</em>[<em>j</em>] := <em>tmp</em>”, as initially the variable “<em>tmp</em>” was holding the first value from left, greater than ‘<em>p</em>’. The partitioning is completed.</li></ul><p>As we see, here we have only 1 cycle of assignments which goes over all the ‘<em>L</em>’ values, and in order to properly rearrange them it requires just “<em>L</em>+1” value assignments, compared to the “3*<em>L</em>/2” assignments of Hoare scheme.</p><p>I prefer to call this new partitioning scheme a “Cyclic partition”, because all the ‘<em>L</em>’ values which should be somehow rearranged, now reside on a single cycle of assignments.</p><p>Here is the pseudo-code of the Cyclic partition algorithm. Compared to the pseudo-code of Hoare scheme the changes are insignificant, but <strong>now we always do 1.5x fewer assignments</strong>.</p><pre>// Partitions sequence A[0..N) with pivot value &#39;p&#39; <br>// by &quot;cyclic partition&quot; scheme, and returns index of <br>// the first value of the resulting right part.<br>function partition_cyclic( A[0..N) : Array of Integers, p: Integer ) : Integer<br>    i := 0<br>    j := N-1<br>    // Find the first value from left, which is not on its place<br>    while i &lt; N and A[i] &lt; p<br>        i := i+1<br>    if i == N<br>        return N  // All N values go to the left part<br>    // The cycle of assignments starts here<br>    tmp := A[i]  // The only write to &#39;tmp&#39; variable<br>    while true<br>        // Move right index &#39;j&#39;, as much as needed<br>        while i &lt; j and A[j] &gt;= p<br>            j := j-1<br>        if i == j  // Check for completion of scans<br>            break<br>        // The next assignment in the cycle<br>        A[i] := A[j]<br>        i := i+1<br>        // Move left index &#39;i&#39;, as much as needed<br>        while i &lt; j and A[i] &lt; p<br>            i := i+1<br>        if i == j  // Check for completion of scans<br>            break<br>        // The next assignment in the cycle<br>        A[j] := A[i]<br>        j := j-1<br>    // The scans have completed<br>    A[j] := tmp  // The only read from &#39;tmp&#39; variable<br>    return j</pre><blockquote>Here lines 5 and 6 set up the start indexes for both scans (‘i’ — from left to right, and ‘j’ — from right to left).</blockquote><blockquote>Lines 7–9 search from left for such a value “A[i]”, which should go to the right part. If it turns out that there is no such value, and all N items belong to the left part, lines 10 and 11 report that and finish the algorithm.</blockquote><blockquote>Otherwise, if such value was found, at line 13 we remember it in the ‘tmp’ variable, thus opening a slot at index ‘i’ for placing another value there.</blockquote><blockquote>Lines 15–19 search from right for such a value “A[j]” which should be moved to the left part. Once found, lines 20–22 place it into the empty slot at index ‘i’, after which the slot at index ‘j’ becomes empty, and waits for another value.</blockquote><blockquote>Similarly, lines 23–27 search from left for such a value “A[i]” which should be moved to the right part. Once found, lines 28–30 place it into the empty slot at index ‘j’, after which the slot at index ‘i’ again becomes empty, and waits for another value.</blockquote><blockquote>This pattern is continued in the main loop of the algorithm, at lines 14–30.</blockquote><blockquote>Once indexes ‘i’ and ‘j’ meet each other, we have an empty slot there, and lines 31 and 32 assign the originally remembered value in ‘tmp’ variable there, so the index ‘j’ becomes the first one to hold such value which belongs to the right part.</blockquote><blockquote>The last line returns that index.</blockquote><p>This way we can write 2 assignments of the cycle together in the loop’s body, because as it was proven in chapter 3, ‘<em>L</em>’ is always an even number.</p><p>Time complexity of this algorithm is also <em>O</em>(<em>N</em>), as we still scan the sequence from both ends. It just does 1.5x less value assignments, so the speed-up is reflected only in the constant factor.</p><p>An implementation of Cyclic partition in the C++ language is present on GitHub, and is referenced at the end of this story [1].</p><p>I also want to show that the value ‘<em>L</em>’ figuring in the Hoare scheme can’t be lowered, regardless of what partitioning scheme we use. Assume that after partitioning, the length of the left part will be “<em>left_n</em>”, and length of the right part will be “<em>right_n</em>”. Now, if looking at the left-aligned “<em>left_n</em>”-long area of the original unpartitioned array, we will find some ‘<em>t1</em>’ values there, which are not at their final places. So those are such values which are greater or equal to ‘<em>p</em>’, and should be moved to the right part anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*VN7QfGukHgAyZQXKW8XKnw.png" /><figcaption><em>Illustration of the sequence before and after partitioning.<br>Length of the left part is “left_n=7” and length of the right part is “right_n=5”.<br>Among the first 7 values of the unpartitioned sequence there are “t1=3” of them <br>which are greater than “p=20” (the yellow ones), and should be somehow moved to the right part.<br>And among the last 5 values of the unpartitioned sequence there are “t2=3” of them <br>which are less than ‘p’ (the light green ones), and should be somehow moved to the left part.</em></figcaption></figure><p>Similarly, if looking at the right-aligned “<em>right_n</em>”-long area of the original unpartitioned array, we will find some ‘<em>t2</em>’ values there, which are also not at their final places. Those are such values which are less than ‘<em>p</em>’, and should be moved to the left part. We can’t move less than ‘<em>t1</em>’ values from left to right, as well as we can’t move less than ‘<em>t2</em>’ values from right to left.</p><p>In the Hoare partitioning scheme, the ‘<em>t1</em>’ and ‘<em>t2</em>’ values are the ones which are swapped between each other. So there we have:</p><blockquote>t1 = t2 = L/2,</blockquote><p>or</p><blockquote>t1 + t2 = L.</blockquote><p>Which means that ‘<em>L</em>’ is actually the minimal amount of values which should be somehow rearranged, in order for the sequence to become partitioned. And the Cyclic partition algorithm rearranges them doing just “<em>L</em>+1” assignments. That’s why I allow myself to call this new partitioning scheme as “nearly optimal”.</p><h3>6. Experimental results</h3><p>It is already proven that the new partitioning scheme is doing fewer assignments of values, so we can expect it to run faster. However, before publishing the algorithm I wanted to collect the results also in an experimental way.</p><p>I have compared the running times when partitioning by the Hoare scheme and by Cyclic partition. All the experiments were performed on randomly shuffled arrays.</p><p>The parameters by which the experiments were different are:</p><ul><li><em>N</em> — length of the array,</li><li>“left_part_percent” — percent of length of the left part (upon <em>N</em>), which results after partitioning,</li><li>running on array of primitive data type variables (32-bit integers) <em>vs.</em> on array of some kind of large objects (256-long static arrays of 16-bit integers).</li></ul><p>I want to clarify why I found it necessary to run partitioning both on arrays of primitive data types, and on arrays of large objects. Here, by saying “large object” I mean such values, which occupy much more memory, compared to primitive data types. When partitioning primitive data types, assigning one variable to another will work as fast as almost all other instructions used in both algorithms (like incrementing an index or checking condition of the loop). Meanwhile when partitioning large objects, assigning one such object to another will take significantly more time, compared to other used instructions, and that is when we are interested to reduce the overall number of value assignments as much as that is possible.</p><p>I’ll explain why I decided to run different experiments with different values of “left_part_percent” a bit later in this chapter.</p><p>The experiments were performed with Google Benchmark, under the following system:</p><blockquote>CPU: Intel Core i7–11800H @ 2.30GHz<br>RAM: 16.0 GB<br>OS: Windows 11 Home, 64-bit<br>Compiler: MSVC 2022 ( /O2 /Ob2 /MD /GR /Gd )</blockquote><h4><em>Partitioning arrays of a primitive data type</em></h4><p>Here are the results of running partition algorithms on arrays of primitive data type — 32 bit integer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUgajHXkuTPGsbsvWfPfqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJ4fRvowipIH-ioloh5oww.png" /><figcaption><em>Running times of partitioning algorithms, on array of 32-bit integers, having length N=10&#39;000.<br>Blue bars correspond to partitioning by Hoare scheme, <br>while red bars correspond to the Cyclic partition algorithm.<br>Partitioning algorithms are run for 5 different cases, based on “left_part_percent” — percent of the left part of array (upon N), that will appear after partitioning. The time is presented in nanoseconds.</em></figcaption></figure><p>We see that there is no obvious correlation between value of “left_part_percent” and relative difference in running times of the 2 algorithms. This kind of behavior is expected.</p><h4><em>Partitioning arrays of “large objects”</em></h4><p>And here are the results of running the 2 partitioning algorithms on array of so called “large objects” — each of which is an 256-long static array of 16-bit random integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhWplWJtrYUp3y0FkNyQ1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JtECAkK-k3EwxvA8Ngscg.png" /><figcaption><em>Running times of partitioning algorithms, on array of large objects <br>(256-long static arrays of random 16-bit integers), having length N=10&#39;000.<br>Blue bars correspond to partitioning by Hoare scheme, <br>while red bars correspond to the Cyclic partition algorithm.<br>Partitioning algorithms are run for 5 different cases, based on “left_part_percent” — percent of the left part of array (upon N), that will appear after partitioning. The time is presented in nanoseconds.</em></figcaption></figure><p>Now we see an obvious correlation: Cyclic partition outperforms the Hoare scheme as more, as the “left_part_percent” is closer to 50%. In other words, Cyclic partition works relatively faster when after partitioning the left and right parts of the array appear to have closer lengths. This is also an expected behavior.</p><h4>Explanation of the results</h4><p><em>— Why does partitioning generally take longer, when “left_part_percent” is closer to 50%?</em></p><p>Let’s imagine for a moment a corner case — when after partitioning almost all values appear in left (or right) part. This will mean that almost all values of the array were less (or greater) than the pivot value. And it will mean that during the scan, all those values were considered to be already at their final positions, and very few assignments of values were performed. If trying to imagine the other case — when after partitioning the left and right parts appear to have almost equal length, it will mean that a lot of value assignments were performed (as initially all the values were randomly shuffled in the array).</p><p><em>— When looking at partitioning of “large objects”, why does the difference in running time of the 2 algorithms become greater when “left_part_percent” gets closer to 50%?</em></p><p>The previous explanation shows that when “left_part_percent” gets closer to 50%, there arises need to do more assignments of values in the array. In previous chapters we also have shown that Cyclic partition always makes 1.5x less value assignments, compared to Hoare scheme. So that difference of 1.5 times brings more impact on overall running time when we generally need to do more rearrangements of values in the array.</p><p><em>— Why is the absolute time (in nanoseconds) greater when partitioning “large objects”, rather than when partitioning 32-bit integers?</em></p><p>This one is simple — because assigning one “large object” to another takes much more time, than assigning one primitive data type to another.</p><p>I also run all the experiments on arrays with different lengths, but the overall picture didn’t change.</p><h3>7. Conclusion</h3><p>In this story I introduced an altered partitioning scheme, called “Cyclic partition”. It always makes 1.5 times fewer value assignments, compared to the currently used Hoare partitioning scheme.</p><p>Surely, when partitioning a sequence, value assignment is not the only type of operation performed. Besides it, partitioning algorithms check values of input sequence “<em>A</em>” for being less or greater than the pivot value ‘<em>p</em>’, as well as they do increments and decrements of indexes over “<em>A</em>”. The amounts of comparisons, increments and decrements are not affected by introducing “cyclic partition”, so we can’t just expect it to run 1.5x faster. However, when partitioning an array of complex data types, where value assignment is significantly more time-consuming than simply incrementing or decrementing an index, the overall algorithm can actually run up to 1.5 times faster.</p><p>The partitioning procedure is the main routine of the QuickSort algorithm, as well as of the algorithm for finding the median of an unsorted array, or finding its <em>k</em>-th order statistic. So we can also expect for those algorithms to have a performance gain up to 1.5 times, when working on complex data types.</p><blockquote>My gratitude to:<br> — Roza Galstyan, for reviewing the draft of the story and suggesting useful enhancements,<br> — Asya Papyan, for careful design of all used illustrations and the cover image ( <a href="https://www.linkedin.com/in/asya-papyan-b0a1b0243/">https://www.linkedin.com/in/asya-papyan-b0a1b0243/</a> ),<br> — David Ayrapetyan, for the spell check ( <a href="https://www.linkedin.com/in/davidayrapetyan/">https://www.linkedin.com/in/davidayrapetyan/</a> ).</blockquote><blockquote>If you enjoyed this story, feel free to find and connect me on LinkedIn ( <a href="https://www.linkedin.com/in/tigran-hayrapetyan-cs/">https://www.linkedin.com/in/tigran-hayrapetyan-cs/</a> ).</blockquote><blockquote>All used images, unless otherwise noted, are designed by request of the author.</blockquote><h3>References:</h3><p>[1] — Implementation of Cyclic partition in C++ : <a href="https://github.com/tigranh/cyclic_partition">https://github.com/tigranh/cyclic_partition</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e38bf7948a5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cyclic-partition-an-up-to-1-5x-faster-partitioning-algorithm-e38bf7948a5f">Cyclic Partition: An Up to 1.5x Faster Partitioning Algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Q-ary search : Up to twice faster than Binary search]]></title>
            <link>https://www.cantorsparadise.com/q-ary-search-up-to-twice-faster-than-binary-search-c213c725f8e1?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c213c725f8e1</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Sun, 26 May 2024 14:36:29 GMT</pubDate>
            <atom:updated>2026-01-16T16:06:00.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Q-ary search : Up to twice faster than Binary search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ExdP7x3SpYX6ufJsvhQ3LQ.png" /></figure><p><em>Faster searching on short and average-sized arrays</em></p><h3><strong>1. Introduction</strong></h3><p>Binary search is one of the basic and brief algorithms in Computer science. Its purpose is to find necessary entry in a sorted sequence of data. Considering that learning Binary search does not require knowledge of any other algorithm, it is generally being taught during the first year of Computer programming courses in many universities worldwide.</p><p>The algorithm was figured out during the years 1957–1962, at the early age of computer programming. Later, some variations of it were introduced, like Exponential search, Interpolation search, or Multiplicative binary search, but its implementation for the general case was not changed.</p><p>The idea which I am going to present in this story came to me after my previous writing “1.8x faster Integer printing algorithm” [1]. Then, after doing necessary implementations and experiments, personally to me, the results came out more impressive than it was expected.</p><p>In this story I am going to:</p><ul><li>Recall the Binary search algorithm,</li><li>Make its analysis, uncovering places for potential optimization,</li><li>Present 3-ary search algorithm,</li><li>Describe its generalization — the Q-ary search algorithm, and</li><li>Make experimental comparisons between all of them.</li></ul><p>The experimental results will show that Q-ary search can perform <strong>up to 2.2 times faster</strong> than Binary search, when running over short and average-length arrays of primitive data types, thus making it useful in such fields, where searches in sorted sequences of data are being done frequently.</p><p>The implementation and comparison between several variants of Q-ary search and Binary search in C++ language can be found in [2].</p><h3><strong>2. Recalling Binary search algorithm</strong></h3><p>Binary search algorithm is used for finding necessary value in a sorted sequence of data. During the search, instead of scanning the sequence from left to right (which is by the way the approach of Linear search), Binary search relies on the fact that the sequence itself is sorted, thus on every step it cuts the sequence in 2 equal parts, and continues searching only in one of them.</p><p>The logic of Binary search is very similar to looking for the meaning of a word in a printed vocabulary. All words are listed there in alphabetical order. So, for example, if we want to find meaning of the word “Facility”, we will not leaf over all pages of that large book, until reaching the words which start with “F”, and later reaching “Facility”, will we? Instead we will open the book somewhere in the middle, where, for example, the word “Property” might be found. We know that “F” comes before “P” in the alphabet, so for finding the word “Facility” we should look before “Property”. That’s why we will concentrate only on the first part of all the pages, thus significantly shortening the search range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*XBn8OlJTndFBgGH_uqs8wg.png" /><figcaption><em>Meeting the word “Property” in the dictionary. <br>The word “Facility” should come before it (the new search range is marked up with green).</em></figcaption></figure><p>Next, we will open somewhere in the middle of the shortened search range, and might find the word “Elevate”. We know that “E” comes before “F” in the alphabet. So for finding “Facility” we should look after the word “Elevate”. This, in turn, cuts the search range in 2 parts and allows us to continue only in the second one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*xzPwSt-fnvrrkwPa5ldQ-A.png" /><figcaption><em>Meeting the word “Elevate” in the dictionary. The word “Facility” should come after it, <br>but also before the previously found word “Property” (the new search range is marked up with green).</em></figcaption></figure><p>This way, on every look-up we will cut the search range in 2 parts, until reaching the page which contains the word “Facility”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*G14yKMvGWGapj5ycLF3Glw.png" /><figcaption><em>After meeting few more words in the dictionary,<br>the word “Facility”, that we were searching for, is found.</em></figcaption></figure><p>This works much faster, than leafing all the pages from the first one to the last, doesn’t it? :-D</p><p>While this example was about finding the necessary word in a printed vocabulary, in computer science, when speaking about Binary search algorithm, people usually mean searching for some number ‘<em>q</em>’ in an increasingly-sorted array ‘<em>A</em>’ of length ‘<em>N</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*D00Uu5J-V2UPurMxULoqng.png" /><figcaption><em>Example of a sorted array “A”, having length “N = 17”, <br>while we search for value “q = 14” there.</em></figcaption></figure><p>The logic is completely the same. Initially the search range (i.e. places where ‘<em>q</em>’ might be found) is the entire array ‘<em>A</em>’. On every step of the algorithm, we look at middle-point ‘<em>m</em>’ of current search range. If value “<em>A</em>[<em>m</em>]” written at that position appears to be less than ‘<em>q</em>’, then we should concentrate the search only in the second half, because if ‘<em>q</em>’ is present, it will necessarily come after position ‘<em>m</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*vymc4bU4jWTKRX7BSTlJXw.png" /><figcaption><em>First step of searching “q = 51” on the same sorted array “A”. The middle-point value is 25 (the highlighted rectangle), so if 51 is present, it should be searched after value 25 (the new search range is marked up with cyan).</em></figcaption></figure><p>And otherwise, if “<em>A</em>[<em>m</em>]” appears to be greater than ‘<em>q</em>’, then we should concentrate the search only in the first half, due to the same reason:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*HvC-OOkdfYhnSKcsbm9EOQ.png" /><figcaption><em>First step of searching “q = 14” on the same sorted array “A”. The middle-point value is still 25 (the highlighted rectangle), so if 14 is present, it should be searched before value 25 (the new search range is marked up with cyan).</em></figcaption></figure><p>This process repeats, and on every step we half down the length of the search range, until reaching a search range of length “1”, after which it will remain just to check that value of ‘<em>A</em>’ for being equal to ‘<em>q</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*eheHaCGbofLaTtWN4f0b4Q.png" /><figcaption><em>The complete binary search for value “q = 14”, on the sorted array “A”.<br>Search ranges for all steps are marked up with cyan arrows, placed from bottom to top.<br>Step 1: Meeting middle-point value “A[8] = 25”, “q” should be searched before it.<br>Step 2: Meeting middle-point value “A[4] = 11”, “q” should be searched after it.<br>Step 3: Meeting middle-point value “A[6] = 18”, “q” should be searched before.<br>Step 4: Meeting middle-point value “A[5] = 14”, which is the value “q” <br>that we were searching for.</em></figcaption></figure><p>Note, when searching in an array of length <em>N</em>, Binary search always performs “<em>log</em><strong>₂</strong><em>N</em>” steps. That is because initially the search range is <em>N</em> elements long, and on every step we half it down. So how many “half-down” operations will be required to bring <em>N</em> into 1? Yes, that is always “<em>log</em><strong>₂</strong><em>N</em>”, rounded up to the nearest larger integer.</p><p>In its current form, Binary search algorithm was figured out during years 1957–1962. The algorithm itself is quite simple and short (requires around 10 lines of code), which, as far as I guess, is probably the reason why since 1962 it was almost not modified.</p><p>The idea which I am going to present in this story, came to me from my previous work “1.8x faster Integer printing algorithm” [1], where I designed a specific optimization of binary search, used to find proper decimal digits (i.e. characters in the range [0, 1, 2, … , 9]). It was needed during conversion of integers (written in computer memory as a sequences of 0s and 1s) into human-readable strings of decimal digits. The optimization was targeted to do as few arithmetical operations as possible, during the conversion. Later I realized that the same “optimized” variant of binary search can be programmed also for the general case, and not just for finding proper digits in the short range [0, 1, 2, … , 9].</p><h3>3. Analysis of Binary search</h3><p>Strangely to me, when speaking about Binary search, often it is just mentioned that during the search of given value ‘<em>q</em>’ in a sorted array of length <em>N</em>, the algorithm does “<em>log</em><strong>₂</strong><em>N</em>” comparisons of ‘<em>q</em>’ with various values of that array. Of course it does so, but the algorithm also does many auxiliary operations, each of which takes its own time from the CPU.</p><p>Let’s observe the following pseudo-code of Binary search:</p><pre>function binary_search_leftmost(A, N, q) is<br>    start := 0<br>    length := N<br>    while length &gt;= 2 do<br>        fragment := floor( length / 2 )<br>        m := start + fragment<br>        if A[m] &lt; q then  // Go to 2&#39;nd part<br>            start := m<br>            length := length - fragment<br>        else  // Go to 1&#39;st part<br>            length := fragment<br>    // Choose between 2 indexes at the end<br>    if a[start] &lt; q<br>        start := start + 1<br>    return start</pre><p>Here we search for the leftmost position of ‘<em>q</em>’ in array ‘<em>A</em>’ of length ’<em>N</em>’. In case if ‘<em>q</em>’ is missing, the algorithm will report index of the first value, greater than ‘<em>q</em>’ (so that will also be the position where ‘<em>q</em>’ should be inserted into the array ‘<em>A</em>’, for it to remain sorted). The variables ‘<em>start</em>’ and ‘<em>length</em>’ identify the current search range: it starts from index ‘<em>start</em>’ and has ‘<em>length</em>’ values in it. Initially the search range is the entire array “<em>A</em>[0..<em>N</em>)”. Variable “<em>fragment</em>” denotes length of the first half of the search range. The variable ‘<em>m</em>’ is the index of the middle-checkpoint. If ‘<em>q</em>’ appears to be greater than the value of the middle-checkpoint “<em>A</em>[<em>m</em>]” (line 7), we should continue the search in the right half. Otherwise (line 10), we continue searching in the left half. On every step of the algorithm, the search range [<em>start</em>, <em>start </em>+ <em>length</em>) is shortened by half. Once “<em>length</em>” reaches 1, we exit the loop and return either position “<em>start</em>” or “<em>start</em>+1” (lines 13, 14).</p><p>Note, when halving the search range, if continuing in right half we have “<em>length := length — fragment</em>” written (line 9), while if continuing in the left half we have written “<em>length := fragment</em>” (line 11). The difference comes from the fact that “<em>length</em>” will not always be an even value, so it will not always be possible to divide it into 2 exactly equal parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Lc3TzulTqLpIx-DS5ntbkg.png" /><figcaption><em>Example of array “A” with odd length “N = 9”. After checking the highlighted middle-point value “A[4] = 21”, <br>we should either continue searching in the 4-long left sub-range “A[0..3]”, or in the 5-long right sub-range “A[4..8]”.</em></figcaption></figure><p>That’s why in such cases our left half will be 1-less than the right half. And as we already have the size of the left half calculated in the “<em>fragment</em>” variable, we can use it to know size of the right half too, by writing “<em>length</em> := <em>length</em> — <em>fragment</em>”. By the way, in case of even “<em>length</em>”, the same formulas still work and produce exactly equal halves.</p><p>Now let’s dive into analysis of the presented pseudo-code.</p><p>First of all, we can note that those “<em>log</em><strong>₂</strong><em>N</em>” comparisons with ‘<em>q</em>’ (line 7) are not the only comparisons performed during the algorithm. The loop’s condition itself does the same amount of comparisons (line 4) when deciding whether to continue the search or not. The algorithm continues as long as the search range [<em>start</em>, <em>start</em> + <em>length</em>) has at least 2 values in it.</p><p>Besides comparisons, there are 1 division and 1 addition operations performed (lines 5, 6), during every step of the algorithm. And addressing the array (“<em>A</em>[<em>m</em>]”, at line 7) also means adding ‘<em>m</em>’ to the starting location of ‘A’, in terms of hardware operations.</p><p>As we will see later in this story, all those auxiliary actions together in fact take more CPU time, than the main comparison (line 6), which means that there might be places for optimization of the algorithm.</p><p>Let’s calculate counts of all elementary operations, performed during one step of the Binary search. We will use all those counts later for comparison purposes. We assume that there is no correlation between values of the array ‘<em>A</em>’ and the value ‘<em>q</em>’, which means that ‘<em>q</em>’ has equal probability of appearing anywhere in the array. In its turn, it means that the branching condition (line 7) will be satisfied with probability of 1/2 on every step. So the “if” branch (lines 8, 9) will run with probability 1/2, as will the “else” branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*GP2Fwa-gaYads9Yr48LIyA.png" /><figcaption><em>Search range of array “A” is divided in 2 almost equal parts. <br>The probability of finding “q” in any of them is equal to 1/2.</em></figcaption></figure><p>Let’s put every line of the pseudo-code in a table, write down probabilities of execution for all lines, and thus, calculate average numbers of all the elementary operations performed, during one step of the algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*wT8tI3EpzJRQJPLJfRO3LA.png" /><figcaption><em>Columns of this table correspond to:<br>1) Line in pseudo-code of the binary search algorithm,</em><br><em>2) Probability of execution of that line, during a single step,</em><br><em>3) The instruction itself, written at that line,</em><br><em>4) Count of comparison operations, performed there,</em><br><em>5) Count of assignments performed on that line,</em><br><em>6) Count of addition, subtraction or multiplications, performed there,</em><br><em>7) Count of division operations,</em><br><em>8) Count of addressing the array by index.</em></figcaption></figure><p>Now let’s calculate average number of times, that every type of elementary operation will be performed during a single step. To do that, for every line we need to multiply number of times the operation is present at that line (columns 4–8) by the probability of execution of that line (column 2), and add that all together:</p><ul><li>For &quot;Comparison&quot; operation we get:<br> 1*1 + 1*1 = 2</li><li>For &quot;Assignment&quot; operation we get:<br> 1*1 + 1*1 + 1*(1/2) + 1*(1/2) + 1*(1/2) = 2 + 3*(1/2) = 3.5</li><li>For &quot;Addition&quot;, &quot;Subtraction&quot;, and &quot;Multiplication&quot; together we get:<br> 1*1 + 1*(1/2) = 1 + 1/2 = 1.5</li><li>For &quot;Division&quot; (happens only at one line):<br> 1*1 = 1</li><li>And for &quot;Array access by index&quot; (again happens only at one line):<br> 1*1 = 1</li></ul><p>Finally, let’s put this results in another table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*2nZoGG-Ghhk7v3z9WjT0lg.png" /><figcaption><em>Average number of times that elementary operations are performed <br>during a single step of Binary search.</em></figcaption></figure><p>Returning to our topic, an important point here also is that the mentioned arithmetical operations are not performed equally fast on modern processors. Some of them might take up to 4–5 times longer than the others. Here is the diagram of how long every elementary operation takes on average:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCKgPdo0Zv6-jOPWEcoNzg.png" /><figcaption><em>Experimental comparison of time (in nanoseconds) spent to perform the 8 types of operations, when each is run 200 times on a random data. <br>The last 2 operations are comparing integers as “a &lt; b” and as “a == b”.<br>We can see that the integer division and remainder calculation operations are taking significantly more time, both for 32-bit and for 64-bit case. <br>Also, we see that integer multiplication is performed almost as fast as addition or subtraction. <br>Assignment is performed faster than all other, which is pretty expected.</em></figcaption></figure><p>This experiment was made with help of Google Benchmark, under the following system:</p><blockquote>CPU: Intel Core i7–11800H @ 2.30GHz<br>RAM: 16.0 GB<br>OS: Windows 11 Home, 64-bit<br>Compiler: MSVC 2022 ( /O2 /Ob2 /MD /GR /Gd )</blockquote><p>Considering all that, can we speed-up the Binary search algorithm?</p><h3>4. 3-ary search</h3><p>As division operation runs on modern processors about 4–5 times longer compared to most of other arithmetical operations, the first idea which might come is to reduce overall number of divisions performed during the algorithm. For that, let’s try to divide the search range not in 2, but in 3 equal parts, within a single step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*HJh2BABYAgUtGX-wtdNPpQ.png" /><figcaption><em>Example of dividing range with “N = 15” values into 3 equal parts. <br>The 2 checkpoints ‘m1’ and ‘m2’ are highlighted.</em></figcaption></figure><p>We will get then 2 intermediate checkpoints <em>m1</em> and <em>m2</em>, and they both might be compared with ‘<em>q</em>’, the value that we are searching for in the sorted array ‘<em>A</em>’.</p><p>But the next idea is that those 2 comparisons will not necessary run during all steps of the algorithm. If ‘<em>q</em>’ appears to be less than the value at the first checkpoint <em>m1</em> (<em>q </em>≤ <em>A</em>[<em>m1</em>]), it will definitely be also less than the value in the second one — <em>m2</em>, as the array is always sorted and we have the condition “<em>A</em>[<em>m1</em>] ≤ <em>A</em>[<em>m2</em>]” satisfied:</p><blockquote><em>“</em>q<em> ≤ </em>A<em>[</em>m1<em>] ≤ </em>A<em>[</em>m2<em>]” ==&gt; “</em>q<em> ≤ </em>A<em>[</em>m2<em>]”</em></blockquote><p>So the value “<em>A</em>[<em>m2</em>]” should be addressed only if ‘<em>q</em>’ appears to be greater than “<em>A</em>[<em>m1</em>]”.</p><p>Let’s write those ideas into the next pseudo-code:</p><pre>function _3_ary_search_leftmost(A, N, q) is<br>    start := 0<br>    length := N<br>    while length &gt;= 3 do<br>        fragment := floor( length / 3 )<br>        m1 := start + fragment<br>        if A[m1] &lt; q then<br>            m2 := m1 + fragment<br>            if A[m2] &lt; q then  // Go to 3&#39;rd part<br>                start := m2<br>                length := length – 2 * fragment<br>            else  // Go to 2&#39;nd part<br>                start := m1<br>                length := fragment<br>        else  // Go to 1&#39;st part<br>            length := fragment<br>    // Linear search at the end<br>    while length &gt; 0 and A[start] &lt; q<br>        start := start + 1<br>        length := length – 1<br>    return start</pre><p>Here, lines [2..16] present the new logic of dividing the search range into 3 equal parts. This algorithm returns exactly the same as the previous pseudo-code did — the index of first occurrence of ‘<em>q</em>’. In case if ‘<em>q</em>’ is missing, it returns index of the first value, greater than ‘<em>q</em>’ (so that will also be the position where ‘<em>q</em>’ should be inserted into the array ‘<em>A</em>’, for it to remain sorted).</p><p>As before, the variables “<em>start</em>” and “<em>length</em>” represent current search range in the array ‘<em>A</em>’, which is “[<em>start</em>, <em>start</em> + <em>length</em>)”. The variable “<em>fragment</em>” is length of 1/3-rd of the search range. Variables ‘<em>m1</em>’ and ‘<em>m2</em>’ are indexes of the 2 checkpoints. First, the value at checkpoint ‘<em>m1</em>’ is compared with ‘<em>q</em>’ (line 7), and only if ‘<em>q</em>’ appears to be greater, location of the next checkpoint ‘<em>m2</em>’ is calculated (line 8), and the value at ‘<em>m2</em>’ is also compared with ‘<em>q</em>’ (line 9). Based on results of those comparisons, in the next step of the algorithm we will either continue searching in the 3-rd part (lines 10, 11), or in the 2-nd part (lines 13, 14), or in the first part (line 16). Note, when continuing search in the first part, the starting position of the search range “<em>start</em>” doesn’t change, that’s why we only modify “<em>length</em>” at line 16.</p><p>Similarly as in the pseudo-code for Binary search, here too when diving into first or second parts we have “<em>length</em> := <em>fragment</em>” written (lines 14, 16), while when diving into the last part we have written “<em>length</em> := <em>length</em> — 2 * <em>fragment</em>” (line 11). Explanation is the same: “<em>length</em>” is not always divisible by 3. And for such cases, the last part will have 1 or 2 more values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*-jAJo3t_lpGJ_YnxMxO9fg.png" /><figcaption><em>Example of array “A” with length “N = 14”, not divisible by 3.<br>The highlighted checkpoint values “A[4] = 17” and “A[8] = 56” <br>split the array in 3 not equal parts: “A[0..3]”, “A[4..7]” and “A[8..13]”.</em></figcaption></figure><p>We already have calculated lengths of first and second parts in the “<em>fragment</em>” variable, so for obtaining length of the last part we do doubling and subtraction.</p><p>Considering that it is a bit problematic to divide search range into 3 parts, once it becomes shorter than 3 values, at the last part of the pseudo-code (lines 18–20) we just linearly scan over those elements, to find the first value that is greater or equal to ‘<em>q</em>’.</p><p>As we are now dividing the search range not in 2 but in 3 parts, I prefer to call this algorithm “3-ary search”.</p><p>Now let’s do a similar calculation of counts of elementary operations, which are performed during one step of 3-ary search algorithm, in a same way as we did in the previous chapter for the Binary search. We assume that the value ‘<em>q</em>’ has equal probability of appearing at any position inside the sorted array ‘<em>A</em>’. That’s why on every step, once the search range is divided into 3 equal parts, we will assume that ‘q’ might be found in every part with equal probability of 1/3, either that is the part [<em>start</em>, <em>m1</em>), or [<em>m1</em>, <em>m2</em>), or [<em>m2</em>, <em>start</em> + <em>length</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*jo3kvI3tTEtRbWv7VjTK4g.png" /><figcaption><em>Search range of array “A” is divided into 3 almost equal parts. <br>The probability of finding “q” in any of them is equal to 1/3. <br>Probability of finding “q” in any of the last 2 parts is 2/3.</em></figcaption></figure><p>This means that the condition “<em>A</em>[<em>m1</em>]&lt;<em>q</em>” (line 7) will be satisfied with probability 2/3, and its “else” branch (line 15) will run with the remaining probability of 1/3. Inside that “if” branch, the next condition “<em>A</em>[<em>m2</em>]&lt;<em>q</em>” (line 9) will run again with probability 1/3 (during a single step), as well as the “else” branch of that condition (line 12). Let’s put that all in a table, and calculate average number of every elementary operation performed, during one step of 3-ary search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*WVLcq2v3vWcIwDFofP-8lA.png" /><figcaption><em>Columns of this table correspond to:<br>1) Line in pseudo-code of the “3-ary search” algorithm,</em><br><em>2) Probability of execution of that line, during a single step,</em><br><em>3) The instruction itself, present at that line,</em><br><em>4) Count of comparison operations, performed there,</em><br><em>5) Count of assignments performed on that line,</em><br><em>6) Count of addition, subtraction or multiplications, performed there,</em><br><em>7) Count of division operations,</em><br><em>8) Count of addressing the array by index.</em></figcaption></figure><p>Now, similar to the way we have done for Binary search, let’s calculate average number of times, that every type of elementary operation is performed during a single step of 3-ary search. To do that, for every line we need to multiply number of times an operation is present at that line (columns 4–8) by the probability of execution of that line (column 2), and add that all together:</p><ul><li>For &quot;Comparison&quot; operation we get:<br> 1*1 + 1*1 + 1*(2/3) = 2 + 2/3 = 2.666...</li><li>For &quot;Assignment&quot; operation we get:<br> 1*1 + 1*1 + 1*(2/3) + 1*(1/3) + 1*(1/3) + 1*(1/3) + 1*(1/3) + 1*(1/3) = <br> = 2 + 2/3 + 5/3 = 2 + 7/3 = 4 + 1/3 = 4.333...</li><li>For &quot;Addition&quot;, &quot;Subtraction&quot; and &quot;Multiplication&quot; together we get:<br> 1*1 + 1*(2/3) + 2*(1/3) = 1 + 2/3 + 2/3 = 1 + 4/3 = 2 + 1/3 = 2.333...</li><li>For &quot;Division&quot; (happens only at one line):<br> 1*1 = 1</li><li>And for &quot;Array access by index&quot; operation we get:<br> 1*1 + 1*(2/3) = 1 + 2/3 = 1.666...</li></ul><p>And finally, let’s add this results to the comparison table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*lAphOpt74kDBeKRQB8oSRA.png" /><figcaption><em>Average number of times that elementary operations are performed <br>during a single step of Binary search and 3-ary search algorithms.</em></figcaption></figure><p>We see that the counts of elementary operations of 3-ary search algorithm are generally greater, than corresponding counts for Binary search algorithm. But the key difference here is that as 3-ary search divides the search range into 3 equal parts on every step, the number of steps performed during it will be “<em>log₃N</em>”, in contrast to “<em>log</em><strong><em>₂</em></strong><em>N</em>” steps of binary search. We also know that:</p><blockquote>log<strong><em>₂</em></strong>N <em>=</em> log<strong><em>₂</em></strong><em>3 * </em>log<em>₃</em>N <em>≈</em> <em>1.585 * </em>log<em>₃</em>N ,</blockquote><p>which means that 3-ary search will do approximately “1.585” times less steps, compared to binary search. So in order to have a fair comparison, we should divide the average counts of operations of 3-ary search by “<em>log</em><strong><em>₂</em></strong>3 ≈ 1.585”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*k3iH-y7f0-u5N5st7wA4hg.png" /><figcaption><em>Average number of times that elementary operations are performed during:<br>a) single step of Binary search algorithm,<br>b) single step of 3-ary search,<br>c) “scaled” step of 3-ary search.</em></figcaption></figure><p>And here is our target! Average count of almost every elementary operations becomes less, compared to corresponding count of Binary search. This refers especially to the division operation, which is the most time-consuming one. Later in this story we will also experimentally compare running times of this two algorithms.</p><h3><strong>5. Q-ary search</strong></h3><p>Obviously, when searching for a value ‘<em>q</em>’ inside a sorted array ‘<em>A</em>’, the idea of dividing current search range into 3 equal parts instead of 2, can be generalized. We can design an algorithm that will always divide the search range into ‘<em>Q</em>’ equal parts, thus producing ‘<em>Q</em>-1’ checkpoints <em>m1</em>, <em>m2</em>, …, <em>m{Q</em>-1<em>}</em> , and inspecting them all from left to right during a single step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ryikEq614hzpSYkZuExDSA.png" /><figcaption><em>Example of dividing range with “N = 16” values into 4 equal parts. <br>The 3 checkpoints ‘m1’, ‘m2’ and ‘m3’ are highlighted.</em></figcaption></figure><p>Here I use uppercase ‘<em>Q</em>’ for denoting the number of parts into which the search range is being divided, and lowercase ‘<em>q</em>’ for denoting the value that we search in the sorted array. So those two are different.</p><p>Similar to as it was for the “3-ary search” algorithm, here also the values “<em>A</em>[<em>m</em>1]”, “<em>A</em>[<em>m</em>2]”, …, “<em>A</em>[<em>m</em>{<em>Q</em>-1}]” will not all necessarily be compared with ‘<em>q</em>’ on every step of the new algorithm. If ‘<em>q</em>’ appears to be less than “<em>A</em>[<em>m</em>1]”, it will be also less than all other checkpoint-values, as the array ‘<em>A</em>’ is sorted, and there is no need to do further comparisons:</p><blockquote><em>“</em>q <em>≤</em> A<em>[</em>m1<em>] ≤ </em>A<em>[</em>m2<em>] ≤ </em>A<em>[</em>m3<em>] ≤ …” ==&gt; “</em>q<em> ≤ </em>A<em>[</em>m2<em>]” , “</em>q<em> ≤ </em>A<em>[</em>m3<em>]” , …</em></blockquote><p>Otherwise, if ‘<em>q</em>’ is greater than “<em>A</em>[<em>m</em>1]”, but less than “<em>A</em>[<em>m</em>2]”, again no more comparisons are required, as it will be less than all remaining check-point values:</p><blockquote><em>“</em>A<em>[</em>m1<em>] ≤ </em>q<em> ≤ </em>A<em>[</em>m2<em>] ≤ </em>A<em>[</em>m3<em>] ≤ </em>A<em>[</em>m4<em>] ≤ …” ==&gt; “</em>q<em> ≤ </em>A<em>[</em>m3<em>]” , “</em>q<em> ≤ </em>A<em>[</em>m4<em>]” , …</em></blockquote><p>And so on…</p><p>Putting this approach into the next pseudo-code, which is “4-ary search”, we get the following:</p><pre>function _4_ary_search_leftmost(A, N, q) is<br>    start := 0<br>    length := N<br>    while length &gt;= 4 do<br>        fragment := floor( length / 4 )<br>        m1 := start + fragment<br>        if A[m1] &lt; q then<br>            m2 := m1 + fragment<br>            if A[m2] &lt; q then<br>                m3 := m2 + fragment<br>                if A[m3] &lt; q then  // Go to 4&#39;th part<br>                     start := m3<br>                     length := length – 3 * fragment<br>                else  // Go to 3&#39;nd part<br>                     start := m2<br>                     length := fragment<br>            else  // Go to 2&#39;nd part<br>                start := m1<br>                length := fragment<br>        else  // Go to 1&#39;st part<br>            length := fragment<br>    // Linear search at the end<br>    while length &gt; 0 and A[start] &lt; q<br>        start := start + 1<br>        length := length – 1<br>    return start</pre><p>This pseudo-code is conceptually similar to the previous one of 3-ary search, so let us skip its explanation and just mention that after dividing current search range into 4 equal parts, the value ‘<em>q</em>’ might be found in any of them with the same probability of 1/4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*HPY9lBPbMt5RJ7kETJLSmA.png" /><figcaption><em>Search range of array “A” is divided into 4 almost equal parts. <br>The probability of finding “q” in any of them is equal to 1/4. <br>Probability of finding “q” in any of the last 3 parts is 3/4.<br>Probability of finding “q” in any of the last 2 parts is 1/2.</em></figcaption></figure><p>So the first “if” statement (line 7) will be satisfied with probability 3/4, the second “if” (line 9) will be entered with probability 2/4 = 1/2, and the third “if” (line 11) will work with probability of 1/4. Putting down this probabilistic analysis into a table, similar to the way we did for the previous 2 algorithms, we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*WhCgrHYb3fbJdp2EHWzpKw.png" /><figcaption><em>Columns of this table correspond to:<br>1) Line in pseudo-code of the “4-ary search” algorithm,</em><br><em>2) Probability of execution of that line, during a single step,</em><br><em>3) The instruction itself, present at that line,</em><br><em>4) Count of comparison operations, performed there,</em><br><em>5) Count of assignments performed on that line,</em><br><em>6) Count of addition, subtraction or multiplications, performed there,</em><br><em>7) Count of division operations,</em><br><em>8) Count of addressing the array by index.</em></figcaption></figure><p>Now again, we should calculate how many times on average each type of operation will run, during a single step. To do that, for every line we need to multiply number of times an operation is present at that line (columns 4–8) by probability of execution of that line (column 2), and add that all together:</p><ul><li>For &quot;Comparison&quot; operation we get:<br> 1*1 + 1*1 + 1*(3/4) + 1*(1/2) = 2 + 3/4 + 2/4 = 3 + 1/4 = 3.25</li><li>For &quot;Assignment&quot; operation we get:<br> 1*1 + 1*1 + 1*(3/4) + 1*(1/2) + 7*(1/4) = 2 + 3/4 + 2/4 + 7/4 = 2 + 12/4 = 5</li><li>For &quot;Addition&quot;, &quot;Subtraction&quot; and &quot;Multiplication&quot; together we get:<br> 1*1 + 1*(3/4) + 1*(1/2) + 2*(1/4) = 1 + 3/4 + 2/4 + 2/4 = 1 + 7/4 = 2.75</li><li>For &quot;Division&quot; (happens only at one line):<br> 1*1 = 1</li><li>And for &quot;Array access by index&quot; operation we get:<br> 1*1 + 1*(3/4) + 1*(1/2) = 1 + 3/4 + 2/4 = 2 + 1/4 = 2.25</li></ul><p>And finally, adding produced results into our comparison table gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*25_m_y7Kk6wUBSo_jN_Q1w.png" /><figcaption><em>Average number of times that elementary operations are performed during:<br>a) single step of Binary search algorithm,<br>b) single step of 3-ary search,<br>c) “scaled” step of 3-ary search,<br>d) single step of 4-ary search,<br>e) “scaled” step of 4-ary search.</em></figcaption></figure><p>We have added 2 rows to the comparison table. One is “4-ary search (one-step counts)”, which represents just the average counts of performed operations during one step of “4-ary search”. The other is “4-ary search (scaled counts)”, which takes into account the fact that 4-ary search algorithm performs twice less steps, than Binary search. That is obvious, because if always dividing the search range into 4 equal parts, we will reach the unit length twice faster, than if always dividing it in 2 equal parts:</p><blockquote>log<em>₂</em>N<em> = </em>log<em>₂4 * </em>log<em>₄</em>N<em> = 2 * </em>log<em>₄</em>N<em> ,</em></blockquote><p>so the last row “4-ary search (scaled counts)” has same values as its previous row, just divided by 2. We need to do that division for keeping the comparison fair between 4-ary search and Binary search, the same way as we divided average counts of 3-ary search over “<em>log</em>₂3 ≈ 1.585”.</p><p>So what do we get for 4-ary search algorithm? Almost all scaled counts are less than scaled counts of 3-ary search, which in their turn were less than corresponding counts for Binary search. And it promises us that the 4-ary search algorithm will run faster than the other two. Experimental comparisons presented in the next chapter will actually confirm this assumption. Let’s note that the maximal gain we have is for the division operation, which is itself the most time-consuming.</p><p>The experimental comparisons will contain analysis also for “5-ary search” and “6-ary search” algorithms. We will see that for some cases even “6-ary search” might be the best choice.</p><p>Title for the algorithm of this story — “Q-ary search”, points that we should not bound ourselves by choosing between 3-ary or 4-ary searches, and that instead we can dynamically choose the value of “<em>Q</em>” — number of equal parts that the search range will be divided into. That choice can be affected by:</p><ul><li>type of objects stored in the array,</li><li>time necessary to compare 2 such objects,</li><li>length of the array,</li></ul><p>as well as other factors.</p><h3>6. Experimental results</h3><p>Let’s confirm all those theoretical assumptions in practice. I have implemented Q-ary search algorithms for <em>Q</em>∈ [2, 6], and tested them on sorted arrays of the following data types:</p><ul><li>32-bit integer,</li><li>64-bit integer,</li><li>64-bit floating-point value,</li><li>string.</li></ul><p>I also compared the algorithms on arrays of different length, starting from <em>N</em>=50, up to <em>N</em>=1&#39;500&#39;000. When testing a certain algorithm on a particular array, multiple Q-ary searches were performed, and their average runtime was taken as result.</p><p>All the experiments were done on the same system, mentioned in chapter 3. Google Benchmark was used to obtain the results.</p><p>The implementation of Q-ary searches in C++ language, with <em>Q</em>∈ [2, 6] can be found on GitHub at [2].</p><h4><em>32-bit integers case</em></h4><p>Here are the results of comparing Q-ary searches / Binary search on arrays of 32-bit integers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhHhqyyBYCXhdcNzWyWBUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVc1dvXOIMmHl8NkQt-OoQ.png" /><figcaption><em>Average time, required to perform a single Binary search<br>/ Q-ary search (Q ∈ [2, 6]), on array of 32-bit integers. <br>Time is presented in nanoseconds.</em></figcaption></figure><p>In each group, the first bar corresponds to C++ / STL standard implementation of Binary search (“<em>std::lower_bound&lt;int&gt;()</em>” algorithm). Next bars correspond to my implementations of Q-ary search, having <em>Q</em>∈ [2, 6].</p><p>For some reasons, STL implementation of Binary search is often slower than my implementation of 2-ary search (which is basically, the same Binary search). After observing the codes of STL implementation, I think a possible reason is that the middle element there is considered separately, and 2 additional increments are being done on the local variables, when continuing the search in the upper half. However, there might be other explanations too.</p><p>We can see that for short and average-sized arrays (<em>N</em>∈ [50, 5&#39;000]) Q-ary search runs around [1.65–2.28] times faster. For example, taking <em>N</em>=500, we see that 6-ary search runs <strong>1.75 times faster</strong>, compared to Binary search / 2-ary search. Once array lengths grows larger than <em>N</em>=50&#39;000, relative behavior of all mentioned algorithms tends not to change, and Binary search wins for all those cases.</p><h4><em>64-bit integers case</em></h4><p>Behavior of Q-ary search algorithms on arrays of 64-bit integers looks quite alike to 32-bit integers case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4gtaNVVHXQUOaWEC3oREA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-6-upR0K6cz07NDPnNI2Q.png" /><figcaption><em>Average time, required to perform a single Binary search <br>/ Q-ary search (Q ∈ [2, 6]), on array of 64-bit integers. <br>Time is presented in nanoseconds.</em></figcaption></figure><p>For array sizes <em>N</em>∈ [50, 5&#39;000] Q-ary search runs around [1.44–2.38] times faster, compared to Binary search. Particularly, when <em>N</em>=5&#39;000, 6-ary search runs <strong>2 times faster</strong> than Binary search / 2-ary search. And for the cases of long arrays (like if <em>N</em>&gt;15&#39;000), Binary search wins.</p><h4><em>64-bit floating point values case</em></h4><p>When searching in arrays of floating-point real values, Q-ary search seems to be even more impressive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7OKv9Gj1RM0573zbLVYPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvawlENjd7Wsrb_jaxgzcw.png" /><figcaption><em>Average time, required to perform a single Binary search <br>/ Q-ary search (Q ∈ [2, 6]), on array of 64-bit floating-point values. <br>Time is presented in nanoseconds.</em></figcaption></figure><p>We see that for array sizes <em>N</em>∈ [50&#39;, 5&#39;000] Q-ary search runs around [1.49–2.59] times faster. Particularly, when <em>N</em>=1&#39;500, 3-ary search runs <strong>2.2 times faster</strong> than Binary search. For cases of long arrays (like if <em>N</em>&gt;15&#39;000), Binary search starts to win.</p><h4>Case of complex data type (strings)</h4><p>I also tried to run Binary search / Q-ary search on arrays of strings (“<em>std::string</em>” objects from STL library), and here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0wxLBbM2q-F3kxnehjgWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBxs4Cib-ek7Khup6NiwAw.png" /><figcaption><em>Average time, required to perform a single Binary search <br>/ Q-ary search (Q ∈ [2, 6]), on array of strings. <br>Time is presented in nanoseconds.</em></figcaption></figure><p>As we see, the results here are different: for each array’s length <em>N</em>, the runtime of an algorithm increases a bit with increase of <em>Q</em>. And, as a consequence, Binary search works a bit faster than its Q-ary search counterparts.</p><p>I explain it relying on the following 2 facts:</p><ul><li>First is that strings are not primitive data types, and comparing 2 strings takes significantly more time, than for example, comparing 2 integers. And as increment of <em>Q</em> in the variants of Q-ary search means also performing more comparisons between objects of the array, it is not a surprise that runtime increase together with the increase of value of <em>Q</em>.</li><li>And the second is that strings (particularly, “<em>std::string</em>” objects of STL library) store actual sequences of characters in the to called “heap” section of the memory. Thus, for comparing 2 strings of the array it is not enough to work only with the memory location of the array itself. Sequences of actual characters of those 2 strings might be found in a completely different location of memory, thus, considering CPU caching mechanism, it slows down comparison of two strings even more.</li></ul><p>So, the time necessary to find a given string in a sorted sequence of strings generally comes down to the number of times that various strings are being compared between each other, because all the auxiliary operations take much less time.</p><h4>Overall remarks</h4><p>All the experiments show that Q-ary search algorithms work faster on short and average-sized arrays, while on long arrays Binary search outperforms them. I explain it by caching mechanism, which is present in all modern processors:</p><ul><li>Large array means that any of the algorithms (Binary search / Q-ary search) on its first steps will address such values of the array, which reside in memory far from each other. Every such addressing will cause a cache miss, and a necessity to load different fragment from RAM into CPU cache. Each such reloading is relatively time-consuming. That’s why for long arrays we should prefer such an algorithm, which does as few memory addressing as possible, and that is definitely the Binary search.</li><li>While short or average-length array means that it entirely can be fit in a cache line of the processor, and there will be no difference which value of the array is going to be addressed next. So CPU caching will not affect the theoretical estimates made in previous chapter, and that’s why for example 6-ary search, on certain cases, works faster than all other considered algorithms.</li></ul><p>I have limited the experiments with such Q-ary searches where <em>Q</em>≤6, but nothing prevents us to implement also 7-ary search, 8-ary search, and so on, as one of them might even outperform all others, on particular datasets.</p><p>Right before publishing this story, I made the same experiments under MinGW 13.2.0 compiler too. There, Q-ary search algorithms still work faster than the Binary search, but the difference in their performance was not that large. I thought all the presented codes are quite simple, and should be compiled in the same way regardless of the compiler. So currently, I am not exactly sure what makes them behave a bit different.</p><p>Experimental results show that Q-ary search can be preferable over Binary search, when we work with arrays of primitive data types, such as integer or floating-point value. Comparing 2 such values is done as fast as, for example, checking the loop’s condition “<strong><em>while </em></strong><em>length &gt;= 4 </em><strong><em>do</em></strong>”, or doing addition, or assigning some value to a variable.</p><p>But when working with more complex data types, for example strings, comparing 2 such objects might take significantly more time than all other elementary operations, performed during the search. And for such cases we’ll probably want to minimize overall number of comparisons. So, Binary search promises to be the best choice then.</p><p>However, let me also point that in practice, algorithms like Binary search are generally performed on primitive data types.</p><h3>7. Conclusion</h3><p>I have presented an optimization of Binary search algorithm, called Q-ary search. For short and average-length arrays of primitive data types, like if array length <em>N </em>∈ [50, 5&#39;000], it can run around <strong>1.75–2.2</strong> times faster than Binary search.</p><p>Thank you for reading till the end!</p><p>Presented algorithm can be used in open-source projects and libraries, under the condition of citing this article.</p><blockquote>Review of the draft made by David Ayrapetyan ( <a href="https://www.linkedin.com/in/davidayrapetyan/">https://www.linkedin.com/in/davidayrapetyan/</a> ),</blockquote><blockquote>If you enjoyed this article, feel free to find and connect to me on LinkedIn ( <a href="https://www.linkedin.com/in/tigran-hayrapetyan-cs/">https://www.linkedin.com/in/tigran-hayrapetyan-cs/</a> ).</blockquote><h3>References</h3><p>[1] — “1.8x faster Integer printing algorithm” : <a href="https://www.cantorsparadise.com/1-8x-faster-integer-printing-algorithm-52d43bd265e0">https://www.cantorsparadise.com/1-8x-faster-integer-printing-algorithm-52d43bd265e0</a></p><p>[2] — Implementation and demo of Q-ary search in C++ : <a href="https://github.com/tigranh/q_ary_search">https://github.com/tigranh/q_ary_search</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c213c725f8e1" width="1" height="1" alt=""><hr><p><a href="https://www.cantorsparadise.com/q-ary-search-up-to-twice-faster-than-binary-search-c213c725f8e1">Q-ary search : Up to twice faster than Binary search</a> was originally published in <a href="https://www.cantorsparadise.com/">Cantor’s Paradise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1.8x faster Integer printing algorithm]]></title>
            <link>https://www.cantorsparadise.com/1-8x-faster-integer-printing-algorithm-52d43bd265e0?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/52d43bd265e0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Fri, 03 May 2024 15:14:02 GMT</pubDate>
            <atom:updated>2026-03-10T15:51:49.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*qPzJ3aNQs_5Y0OyCUmUWfg.png" /></figure><p><em>A new algorithm, which does no division or remainder calculation</em></p><h3><strong>1. Introduction</strong></h3><p>It is a well known fact that everything, including numbers, is represented in computer memory as various sequences of <strong>0</strong>s and <strong>1</strong>s. For example,</p><blockquote>number 34 is represented as “100010”,<br>and number 14 is stored as “1110”.</blockquote><p>So when any integer is being printed to the screen or into a text file, a need arises to convert it into familiar representation of decimal digits — from ‘<strong>0</strong>’ to ‘<strong>9</strong>’.</p><p>Such operation is called “integer to string conversion”, and should be done every time before printing an integer. Currently few algorithms exist for doing such conversion.</p><p>In this story I am going to:</p><ul><li>Describe the standard algorithm for converting integers to strings (chapter 2),</li><li>Walk over its existing optimizations (chapter 3),</li><li>Present my new algorithm, which addresses integers printing in a completely novel way (chapters 4 and 5),</li><li>Describe how my new algorithm can print integers in other bases too (chapter 6),</li><li>Describe 4 optimizations for the new algorithm (chapter 7),</li><li>Present experimental comparison of all mentioned algorithms (chapter 8).</li></ul><p>Experimental comparisons will show that my new algorithm converts 32-bit integers to strings faster by around <strong>43–45%</strong>, compared to the currently standard conversion algorithm, and for 64-bit integers it works faster by around <strong>57–62%</strong>.</p><p>By the way, this work addresses the same problem as my previous writing “34% faster Integer to String Conversion algorithm” [3]. But here the obtained performance gain is higher.</p><p>I should mention that printing integers is not a bottleneck for most of modern computer programs, as generally, only a tiny percent of calculated numbers is being sent to print. Most of numbers and values participate only in intermediate calculations, thus no need arises for converting them into strings.</p><p>However, there are some types of programs which automatically generate large text files (like *.csv, *.xml, *.json), which usually contain lots of numbers, written in the familiar decimal notation. So there arises need to convert tons of integers into corresponding strings, and that is when performance of integer to string conversion algorithm becomes important. For example, that can be the case when working in Data Science or Machine Learning fields, and exporting large datasets into text files.</p><h3><strong>2. The standard printing algorithm</strong></h3><p>As printing integers is one of the most common operations, which basically is a conversion of integer to a string, corresponding functions are implemented in standard libraries of all modern programming languages.</p><p>And the algorithm used in those functions to print input number ’<em>N</em>’ is nearly the same, based on repeatedly obtaining value of the last digit of ’<em>N</em>’, and dropping that digit out, thus making it possible to continue with the remaining part of ‘<em>N</em>’.</p><p>In order to obtain the last digit of ’<em>N</em>’ we calculate remainder of its division upon 10:</p><blockquote>digit := N mod 10</blockquote><p>and in order to drop the last digit, we do the actual division itself:</p><blockquote>N := ⌊ N / 10 ⌋</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*yaRM76oQYT207preZKbdzQ.png" /><figcaption><em>Given an integer N, how its last digit <br>and the remaining part are being computed.</em></figcaption></figure><p>Note, here and later in this story, when dividing 2 integers, we will consider only the whole part of the result.</p><p>Those 2 operations: remainder calculation and integer division, can produce the complete sequence of digits of ’<em>N</em>’, when put in a loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*2jOesALjxx_HGBjXPvsKvA.png" /><figcaption><em>Operations for printing number “5173”:<br>Step 1: 5173 % 10 = 3 (storing digit “3”) , 5173 / 10 = 517 (continuing with 517),<br>Step 2: 517 % 10 = 7 (storing digit “7”) , 517 / 10 = 51 (continuing with 51),<br>Step 3: 51 % 10 = 1 (storing digit “1”) , 51 / 10 = 5 (continuing with 5),<br>Step 4: As “5 &lt; 10”, just storing the last digit “5”.<br>Step 5: (not illustrated) reversing order of stored digits and printing them.</em></figcaption></figure><p>Note, the algorithm obtains digits of ’<em>N</em>’ in reverse order — from right to left. So if we are going to print them on screen or into a text file, we should also reverse the obtained sequence of digits.</p><p>If writing pseudo-code for the standard integer printing algorithm, it might result in something like this:</p><pre>var result[0 .. 25] : Array of Characters  // Assume 25 characters at most<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into &#39;result&#39; array.<br>procedure print( N: Integer )<br>    i := 0  // Index over &#39;result&#39; array<br>    while N &gt; 0<br>        result[ i ] := &#39;0&#39; + (N mod 10)  // Take the last digit<br>        N := ⌊ N / 10 ⌋   // Pick out the last digit<br>        i := i+1<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character<br>    reverse array result[0 .. i-1]</pre><p>By the way, in this and all subsequent pseudo-codes, we will not handle the case of printing number “0”. According to the presented pseudo-code, for input <em>N</em>=0 an empty sequence will be produced. That’s why in all printing algorithms, the case of <em>N</em>=0 is handled in a separate branch. We will just skip that branch for compactness of pseudo-codes.</p><p>The presented algorithm is simple and can be easily implemented in 3–4 lines of code. The only issue with it is that it uses 2 relatively time-consuming operations when obtaining every digit of ’<em>N</em>’: those are integer division and remainder calculation. The benchmarking presented below illustrates which of the basic arithmetical operations are more time-consuming on modern CPUs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-99K52RJmjfTs2Eb0-VAQ.png" /><figcaption><em>Experimental comparison of time (in nanoseconds) spent to perform the <br>8 types of operations, when each is run 200 times on a random data. <br>The last 2 operations are comparing integers as “a &lt; b” and as “a == b”.<br>We can see that the integer division and remainder calculation operations<br>are taking significantly more time, both for 32-bit and for 64-bit case. <br>Also, we see that integer multiplication is performed almost as fast as addition or subtraction. <br>Assignment is performed faster than all other, which is pretty expected.</em></figcaption></figure><p>The experiments were made with Google Benchmark, under the following system:</p><blockquote>CPU: Intel Core i7–11800H @ 2.30GHz<br> RAM: 16.0 GB<br> OS: Windows 11 Home, 64-bit<br> Compiler: MSVC 2022 ( /O2 /Ob2 /MD /GR /Gd )</blockquote><p>So can we do it better? Maybe we can figure out an algorithm which for printing given integer ’<em>N</em>’ will use neither integer division, nor remainder calculation?</p><h3>3. Existing optimizations</h3><p>Before describing the new algorithm, I want to briefly walk over the existing optimizations, which can speed-up presented standard algorithm.</p><h4><em>Optimization 1</em></h4><p>The first optimization is about eliminating the need of the last “reverse” operation. It is well described in [1]. For that, we should write obtained digits of input number ’<em>N</em>’ in the buffer, right in the order that they should have on the screen. And as the standard algorithm produces digits of ’<em>N</em>’ from right to left, we should also write them in the buffer from right to left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*ITVEsIRvUKuQXDQtfYJ3tw.png" /><figcaption><em>Filling produced digits into result array from right to left,<br>directly in the order they should have at the end.</em></figcaption></figure><p>To enable this optimization, pseudo-code should be changed insignificantly:</p><pre>var result[0 .. 25] : Array of Characters  // Assume 25 characters at most<br><br>// The function takes integer &#39;N&#39; to be printed, and returns position <br>// of its converted first character in the &#39;result&#39; array.<br>function print( N: Integer ) : Integer<br>    result[ 25 ] := &#39;\0&#39;  // Place the terminating &#39;null&#39; character at the end<br>    i := 25  // Index over &#39;result&#39; array<br>    while N &gt; 0<br>        i := i-1  // Here we go to left, for placing the next digit<br>        result[ i ] := &#39;0&#39; + (N mod 10)  // Take the last digit<br>        N := ⌊ N / 10 ⌋  // Pick out the last digit<br>    return i  // Position from where the converted integer starts</pre><p>A small drawback of this optimization is that if 2 input numbers have different count of digits, then after writing them in the buffer, their first digits will appear in different positions. So in some sense, it is hard for us to control the starting position of digits of input numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*FCzQ71LK9ygQO4IpW15btA.png" /><figcaption><em>Drawback of optimization 1: numbers with different <br>count of digits will start in the output array from different positions.</em></figcaption></figure><p>However, practically that is almost never an issue, as obtained digits are being promptly sent to screen or to a text file, and thus do not remain in memory for long time.</p><h4><em>Optimization 2</em></h4><p>The second optimization is about obtaining 2 digits of input number ’<em>N</em>’, during a single step. It is well described in [1] and [2]. Here, instead of repeatedly calculating remainder of division of ’<em>N</em>’ over 10, we will calculate remainder of its division over 100.</p><p>So in order to obtain the last 2 digits of ’<em>N</em>’, we will calculate:</p><blockquote>digits := N mod 100</blockquote><p>And to drop them both out of ’N’ we will do:</p><blockquote>N := ⌊ N / 100 ⌋</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*fjPLGBurLli8e33M9hhzMQ.png" /><figcaption><em>Operations for printing number “3249376” with second optimization enabled:<br>Step 1: 3249376 % 100 = 76 (storing digits “76”) , 3249376 / 100 = 32493 (continuing with 32493),<br>Step 2: 32493 % 100 = 93 (storing digits “93”) , 32493 / 100 = 324 (continuing with 324),<br>Step 3: 324 % 100 = 24 (storing digits “24”) , 324 / 100 = 3 (continuing with 3),<br>Step 4: As “3 &lt; 100”, just storing the last digit “3”</em></figcaption></figure><p>However, in order to be able to efficiently print the obtained 2 digits after having result of “<em>N</em> mod 100”, we should have prepared an array of length 100, with values being the pairs of digits:</p><blockquote>[“00”, “01”, “02”, “03”, … , “97”, “98”, “99”].</blockquote><p>So indexes of the array will have range [0..99] (which corresponds to all possible remainders “<em>N</em> mod 100”), and values of the array will be pairs of digits, each pair representing printed value of that remainder.</p><p>By using this optimization, number of integer division and remainder calculation operations is reduced almost by half.</p><p>However, I want to point out here that even with both these optimizations enabled, we still do a number of integer division and remainder calculation operations — proportional to the count of digits of ‘<em>N</em>’.</p><h4><em>My previous algorithm</em></h4><p>Before moving to the next chapter, I also want to mention my previous story “34% faster Integer to String Conversion algorithm” [3], where I proposed another algorithm called “LR printer”, which doesn’t use remainder calculation at all. Instead, in order to obtain every digit of input number ’<em>N</em>’ it does:</p><blockquote>1 integer division,<br>1 multiplication, and<br>1 subtraction.</blockquote><p>And as the last 2 operations are performed around 4–5 times faster on modern CPUs (compared to remainder calculation or integer division), the result performance was around 25–38% faster for printing 32-bit integers, and around 40–58% faster for 64-bit integers.</p><p>In contrast to existing approaches, “LR printer” obtains digits of ’<em>N</em>’ from left to right, directly in the order they should be printed to screen or to a text file.</p><p>For obtaining the first digit of ’<em>N</em>’ (assuming ’<em>N</em>’ has ‘<em>L</em>’ digits), it calculates:</p><blockquote>digit := N / 10^(L-1),</blockquote><p>And for dropping the first digit out of ’<em>N</em>’ it does:</p><blockquote>N := N — digit * 10^(L-1).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*jicYlv2M7YW0W6Q6gY-5_A.png" /><figcaption><em>Examples of obtaining left-most digits of given integers, <br>and picking them out.</em></figcaption></figure><p>There, all necessary powers of 10 are precalculated and used during program’s entire execution.</p><p>The second optimization about getting 2 digits of ’<em>N</em>’ during a single step, is also invokable on “LR printer”.</p><p>However, my previous algorithm still relied on integer division, which is a relatively slow operation. So can we eliminate it too, and use only the fastest arithmetics…?</p><h3><strong>4. The new algorithm for case of binary numeral system (<em>base</em>=2)</strong></h3><p>In this story, I am going to propose a completely different approach for converting integers from binary to decimal representation. The algorithm described here will exclude both integer division and remainder calculation operations, which are the ones that take more computational time, than all other arithmetical operations. Instead, in order to obtain 1 decimal digit of the input number my algorithm will do 1 multiplication, up to 5 comparisons and up to 5 subtractions.</p><h4><em>About binary numeral system</em></h4><p>We already mentioned at the beginning of this story, that in computer memory numbers are stored in binary format — as sequences of 0s and 1s. So if we are going to print them right in that way, no transformation is required.</p><p>However, as the algorithm that I am going to describe came to me when I was working with binary numbers, and as its behavior in binary numeral system is simpler compared to the decimal system’s case, let me start its description from the binary case. So, I suggest us to temporary forget how numbers are stored in computers internally, and just try to figure out binary digits (0s and 1s) of given integer ’<em>N</em>’, as if doing that on a piece of paper, without computers.</p><p>In binary numeral system, each digit has its weight. Weight of the last digit is 1, and weight of every previous digit is twice larger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*IK9VPcKAmqzqFHxhdCaYcw.png" /><figcaption><em>Weights of digits for binary positional numeral system.</em></figcaption></figure><p>If a certain digit of the binary number is 1, it means that we, in a sense, “use” that weight, in order to obtain necessary value of ’<em>N</em>’. And if it is 0, then we, in a sense, “skip” that weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*KB9XVt1GJxFI4OxiU4VQ7g.png" /><figcaption><em>Example of how a number ‘N=25’ is being constructed in binary positional system.<br>We just mention from left to right the weights that should sum up to ‘N’.<br>Those weights are 16, 8 and 1, so we have ‘1’ at corresponding positions.<br>The other weights are not used so we have ‘0’ in the remaining positions.</em></figcaption></figure><p>Having ‘<em>m</em>’ binary digits, why is it always possible to obtain any number ’<em>n</em>’ from range [0,2^<em>m</em>)? Well, we can illustrate that. In case of ‘<em>m</em>’ binary digits, the first digit will have weight 2^(<em>m</em>-1). So using it (making it 1) will result in 2^(<em>m</em>-1) increase of ’n’, which is actually half of the overall range [0, 2^<em>m</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*LtX1iGeHCMTjeSSvw3Ooog.png" /><figcaption><em>Considering that we have only 6 binary digits, <br>so the representable numbers range is [0, 2⁶) = [0, 64), how the value <br>of the first digit affects further range of numbers that we can construct. <br>Skipping the first digit (making it 0) leaves us in the first half of total range [0, 2⁶), <br>while using it (making it 1) takes us to the second half of that range.</em></figcaption></figure><p>So the remaining <em>m</em>-1 digits will be used to find proper point either on the first half of illustrated range, or on the second half, both of which are now 2^(<em>m</em>-1) long.</p><p>The second digit has weight 2^(<em>m</em>-2). So regardless in which half we currently are, using it (making it 1) will result in 2^(<em>m</em>-2) increase of ’n’, which is now one quarter of the overall range [0, 2^<em>m</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*8nA2_t_BKaZR-6f8genORw.png" /><figcaption><em>Considering that we have only m=6 binary digits, how values <br>of the first 2 digits affects further range of numbers that we can construct.</em></figcaption></figure><p>Continuing with same logic, third digit will always have weight 2^(<em>m</em>-3), and regardless of which quarter we are in, using it (making it 1) will result in 2^(<em>m</em>-3) increase of the number being written, which is 1/8-th of the overall range [0, 2^<em>m</em>). While not using it (making it 0) will keep the written number unchanged, in a sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*do7FJA_wntZnE1qH7dtrtw.png" /><figcaption><em>Considering that we have only m=6 binary digits, how values <br>of the first 3 digits partition the total range [0, 2⁶) into 8 sub-ranges, <br>where the number ’N’ being constructed can reside.<br>The light yellow sub-ranges are reachable when not using 3rd digit (making it 0),<br>while the orange sub ranges are reachable when using it (making it 1).</em></figcaption></figure><p>This process of splitting remaining ranges into halves continues until the last digit. At that point of time, with help of the first ‘<em>m</em>-1’ digits we will be able to produce all even numbers of the overall range [0, 2^<em>m</em>). Weight of the last digit is always 1. So using it (making it 1) will result in increase of ’<em>n</em>’ by 1, thus changing it from even to the next odd value on the numbers line. And not using it (making it 0) will keep the produced even number ’<em>n</em>’ unchanged.</p><p>That is how ‘<em>m</em>’ binary digits are able to produce any number from range [0,2^<em>m</em>).</p><p>We can observe a complete example of such diagram. Let’s take now 4 binary digits (<em>m</em>=4), which will enable us to write numbers in range [0, 2⁴) = [0, 16).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*yLrYydlPJOLsn70015W77w.png" /><figcaption><em>Diagram for 4 binary digits, allowing to represent numbers [0, 2^m) = [0, 16). <br>Path for number n=11 is marked with dark green. <br>Path for number n=6 is marked with light green.</em></figcaption></figure><p>Weights of those 4 digits are [8, 4, 2, 1]. We can see that for example in order to write number 11 we should use 1st digit (+8 to the value), not use 2nd digit, use 3rd one (+2 to the value) and also use the last one (+1 to the value), which will result in binary sequence “1011”. That “path” is highlighted on the diagram with dark green.</p><p>Another example, to write number 6, we should not use 1st digit, then use the 2nd one (+4 to the value), use also the 3rd one (+2 to the value), and not use the last one, resulting in “0110” binary sequence, highlighted on the diagram with light green.</p><p>One important note for binary numeral system (as well as generally for any positional system) is that sum of weights of the last ‘<em>k</em>’ digits is always one-less than weight of ‘<em>k</em>+1’-th digit from right. This means that putting ‘1’ on all the last ‘<em>k</em>’ digits and ‘0’ on ‘<em>k</em>+1’-th digit (from right) will result in such a value, which will be 1-less than if putting the opposite digits there. For example, taking ‘<em>k</em>=3’:</p><blockquote>23 in binary is “10111”, while<br>24 in binary is “11000”.</blockquote><p>By the way, this is totally similar to our regular decimal numeral system. We know that putting ‘0’ on some ‘<em>k</em>+1’-th position from right and putting ‘9’ (the maximal digit) on remaining ‘<em>k</em>’ positions will result in a number that is one less than if putting ‘1’ as ‘<em>k</em>+1’-th digit and ‘0’ (the minimal digit) on the remaining ‘<em>k</em>’ positions. For example, the values:</p><blockquote>150&#39;999, and<br>151&#39;000.</blockquote><p>Note, from later on, when describing positions of digits we will always count them from right to left.</p><h4>The algorithm for case “base=2”</h4><p>Now, how exactly this interpretation of binary numeral system will help us to derive a faster integer printing algorithm? Quite straightforward: we will print binary digits of given number ’<em>n</em>’ directly from left to right (in contrast to current approaches of printing digits in reverse order), on each step comparing ’<em>n</em>’ with the weight of current digit.</p><p>If ’<em>n</em>’ is less than weight of current digit, then we should definitely not use that digit, and write 0 there. Because otherwise, writing 1 will increase the number being written in such a way that it will become larger than ’<em>n</em>’, and later, writing 0 even on the all consequent positions, will not bring us to the necessary value of ‘<em>n</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*u-_1TrtlVmN-mbBTZhvpFw.png" /><figcaption><em>Using weight 8 (red arrow), when it was necessary to obtain <br>number 5 (green arrows). Regardless of what next <br>weights will be used, number 5 is no more reachable.</em></figcaption></figure><p>In the other case, if ’<em>n</em>’ is greater or equal to weight of current digit, we should definitely use it, by writing 1 at the current position. Because otherwise, if we write 0 there, the number being written will always remain less than ’<em>n</em>’, even if ‘1’ is put later on all the consequent positions. Putting 1 on all positions to right from ‘<em>k</em>’ will give us additional sum ‘2^<em>k</em>-1’, which is one less than of what we could have obtained, in case of putting ‘1’ at the current position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*1NuVR9hUesRuOaGtHjbPyA.png" /><figcaption><em>Skipping weight 8, when it was necessary to obtain number 9 (green arrows).<br>Using even all subsequent weights 4, 2 and 1 (red arrows) <br>will still result in less than the necessary value n=9.</em></figcaption></figure><p>After properly printing the current digit, in order to be able to continue the algorithm iteratively, we should decrease ’<em>n</em>’ by the weight of current digit, only if that digit was used (if we wrote 1), and proceed to the next digit. This decrease will reflect the fact that we already “presented” corresponding “fragment” ‘2^<em>k</em>’ of ’<em>n</em>’ which is equal to weight of current digit, so it remains for us to “present” only the remaining “fragments”.</p><p>Let’s see an example of complete printing of number ‘<em>n</em>=22’. In binary notation, 22 is represented as “10110”, so that is what we should get at the end. Weights of the last 5 digits in binary numeral system are [16, 8, 4, 2, 1].</p><pre>Iteration 1:  n = 22<br>    n ≥ 16<br>    printing &quot;1&quot;  ;  n := n – 16<br>Iteration 2:  n = 6<br>    n &lt; 8<br>    printing &quot;0&quot;  ;  &lt;no changes to &#39;n&#39;&gt;<br>Iteration 3:  n = 6<br>    n ≥ 4<br>    printing &quot;1&quot;  ;  n := n – 4<br>Iteration 4:  n = 2<br>    n ≥ 2<br>    printing &quot;1&quot;  ;  n := n – 2<br>Iteration 5:  n = 0<br>    n &lt; 1<br>    printing &quot;0&quot;  ;  &lt;no changes to &#39;n&#39;&gt;</pre><p>We can now write the pseudo-code of printing routine for given number ’<em>n</em>’ in binary positional system:</p><pre>var powers_of_2[0 .. 33] : Array of Integers <br>        = { 1, 2, 4, 8, 16, 32, <br>                64, 128, 256, 512, ... <br>                ... , 1&#39;073&#39;741&#39;824, 2&#39;147&#39;483&#39;648 }<br>        // Precalculated powers of 2, which will be used during print<br><br>var result[0 .. 35] : Array of Characters  // Assume at most 35 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// binary digits into the &#39;result&#39; array.<br>procedure print_in_binary( N: Integer )<br>    L := calculate_binary_digits_count( N )<br>    i := 0  // Index over the &#39;result&#39; array<br>    while L &gt; 0<br>        if N &gt;= powers_of_2[ L-1 ]<br>            result[ i ] := &#39;1&#39;  // Write digit &#39;1&#39; in the result<br>            N := N – powers_of_2[ L-1 ]<br>        else<br>            result[ i ] := &#39;0&#39;  // Write digit &#39;0&#39; in the result<br>        i := i+1  // Prepare to next iteration, and<br>        L := L-1  // ... adjust remaining count of digits of &#39;N&#39;<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character</pre><p>You probably noted that both in the example of printing number 22 as “10110”, and in this pseudo-code, we acted like the count of binary digits of the input number ’<em>n</em>’ is already known to us:</p><ul><li>in the example of printing 22 we started from weight 16, which is 5-th power of 2,</li><li>in the pseudo-code we called some function ‘calculate_binary_digits_count()’, and remembered obtained count of digits of ’<em>n</em>’ in variable ‘<em>L</em>’.</li></ul><p>So here I want to mention that obtaining the count of binary digits of ’<em>n</em>’ is not an issue, if we have precalculated all the powers of 2. Let’s take a look on how the first 5 powers of 2 are written in binary:</p><blockquote>1, which is 2⁰ is written as “1”,<br>2, which is 2¹ is written as “10”,<br>4, which is 2² is written as “100”,<br>8, which is 2³ is written as “1000”,<br>16, which is 2⁴ is written as “10000”,<br>… and so on.</blockquote><p>So we see that the value ‘2^(<em>k</em>-1)’ is the smallest value, which uses ‘<em>k</em>’ binary digits. From there, the value ‘(2^<em>k</em>)-1’ is the largest one which uses ‘<em>k</em>’ binary digits, as its next value ‘2^<em>k</em>’ uses ‘<em>k</em>+1’ digits. This means that just iterating over precalculated powers of 2, until reaching such power which is greater than ’<em>n</em>’, will show us the count of binary digits that ’<em>n</em>’ has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*YMGBx1JS6B39S2-dTXQ2BA.png" /><figcaption><em>How the count of binary digits L is being calculated for number N = 12.<br>We sequentially compare N to powers of 2, until N becomes less.<br>That happens on power 16 which is 2⁴, so we conclude that L=4.</em></figcaption></figure><p>Hence, turning this into pseudo-code, and writing the function ‘calculate_binary_digits_count()’ will result in the following:</p><pre>// This function takes integer &#39;N&#39; and returns count of its binary digits.<br>function calculate_binary_digits_count( N: Integer ) : Integer;<br>    // Check case of numbers with maximal count of digits<br>    if N &gt;= powers_of_2[ 31 ]  // Compare with maximal power of 2<br>        return 32  // The count of digits for such numbers<br>    // Regular case<br>    L := 0<br>    while N &gt;= powers_of_2[ L ] <br>        L := L+1<br>    return L</pre><p>The initial “if” check here is required for such input numbers ’<em>n</em>’, which are greater or equal to the largest precalculated power of 2 (2³¹ = 2&#39;147&#39;483&#39;648). If skipping that check, an overflow will happen when trying to address the next power of 2 (2³², which is absent from the array). And if ’<em>n</em>’ is not that large, we find the count of its binary digits with the “while” loop, that comes next.</p><p>Concluding this chapter, the important fact is that in order to print ’<em>n</em>’, <strong>our algorithm does</strong> <strong>only comparisons and subtractions</strong>. When comparing to standard printing algorithms, ours doesn’t use any relatively time-consuming operations such as integer division or remainder calculation. In order to obtain the value of every digit we do only 1 comparison, and possibly 1 subtraction.</p><h3>5. The new algorithm for case of decimal numeral system (<em>base</em>=10)</h3><p>Can we apply a similar approach for printing number ’<em>n</em>’ in our familiar, decimal numeral system? If we are going to do so, it will not be enough to iteratively compare ’<em>n</em>’ with some weights, as for every digit we should choose not just between yes or no (1 or 0), but between 10 different options (digit values from ‘0’ to ‘9’).</p><p>We know the weights of digits in decimal numeral system. Weight of the last digit is still 1, and weight of every previous digit is 10 times larger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*ahwyG52piysQS730p2iLUA.png" /><figcaption><em>Weights of digits in decimal positional system.</em></figcaption></figure><p>Can we preserve the logic described in previous chapter (for case <em>base</em>=2) here too, so values of digits will be obtained again only by comparisons and subtractions?</p><p>The first idea which might come to us is to do something like linear search among digits [0..9]. So in order to figure out the value of every digit we will repeat the comparison and subtraction operations several times. For example if <em>n</em>=735, and we are figuring out its first digit from left, weight of that digit is 10²=100, so we will repeatedly compare ’<em>n</em>’ with 100 and subtract that weight from ’<em>n</em>’, as long as the latter one remains positive or 0.</p><pre>Step 1:  n = 735  ;  digit = 0<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 2:  n = 635  ;  digit = 1<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 3:  n = 535  ;  digit = 2<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 4:  n = 435  ;  digit = 3<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 5:  n = 335  ;  digit = 4<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 6:  n = 235  ;  digit = 5<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 7:  n = 135  ;  digit = 6<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1<br>Step 8:  n = 35   ;  digit = 7<br>    n &lt; 100<br>    &lt;current digit is 7, proceeding to next digit&gt;</pre><p>The condition ‘<em>n</em> ≥ 100’ was satisfied 7 times, so the value of the first digit from left is ‘7’, and we will continue figuring out value of next digit, having ’<em>n</em>’ decreased to: ‘735–7*100 = 35’.</p><p>Then, weight of the next digit is 10, so we will repeatedly compare ’<em>n</em>’ (currently 35) with 10, and subtract 10 from it, as long as it remains positive or 0. Obviously that will be repeated 3 times, altering ’<em>n</em>’ to: ’35–3*10 = 5&#39;.</p><p>And value of the last digit is already equal to the current value of ’<em>n</em>’ (as at this point of time ’<em>n</em>’ becomes a 1-digit number).</p><p>With this linear search we will do up to 10 comparisons and 9 subtractions when figuring out every digit of ’<em>n</em>’. If we will try to illustrate that logic of digit search, it might graphically result in something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*SKvW4Wh--PLz29074jQ3Qw.png" /><figcaption><em>Illustration of how the proper decimal digit is being searched linearly.</em></figcaption></figure><p>Can we do it better? Yes, if we’ll replace <strong>linear search</strong> with <strong>binary search</strong>!</p><p>Let’s see: when we were figuring out the first digit of <em>n</em>=735, we were iteratively comparing it with weight 100, and were subtracting that weight from ’<em>n</em>’. What if we will cut the digit search range into half? Let’s compare it right with 5*100=500 instead:</p><pre>Step 1:  n = 735  ;  digit = 0<br>    n ≥ 500<br>    n := n – 500  ;  digit := digit + 5</pre><p>So we know now that the first digit should be in range [5..9]. Let’s cut this range into half too, now comparing ’<em>n</em>’ either with 2*100=200 or with 3*100=300:</p><pre>Step 2:  n = 235  ;  digit = 5<br>    n &lt; 300<br>    &lt;we don&#39;t make any alterations then&gt;</pre><p>As current ’<em>n</em>’ turns out to be less than 3*100, the range search cuts down from [5..9] to [5..7]. Now lets compare ’<em>n</em>’ with 100:</p><pre>Step 3:  n = 235  ;  digit = 5<br>   n ≥ 100<br>   n := n – 100  ;  digit := digit + 1</pre><p>Now ’<em>n</em>’ appeared to be greater than 100, which cuts search range of the first digit from [5..7] to [6..7]. And so there is need to compare ’<em>n</em>’ with 100 one more time:</p><pre>Step 4:  n = 135  ;  digit = 6<br>    n ≥ 100<br>    n := n – 100  ;  digit := digit + 1</pre><p>Which results in:</p><pre>    n = 35  ;  digit = 7</pre><p>So we have properly calculated the first digit of <em>n</em>=735 as ‘7’, and reduced ’<em>n</em>’ from 3-digit value 735 into 2-digit value 35, which allows us to perform similar operations for finding the next digit too.</p><p>While searching the next digit, we will again start with possible range of digits [0..9] and will repeatedly cut it into 2 (almost) equal parts, and continuing in the necessary half. The only difference is that comparisons and subtractions will be made now with the factor of 10¹=10, and not 10²=100.</p><pre>Step 1:  n = 35  ;  digit = 0<br>    n &lt; 50<br>    &lt;we don&#39;t make any alterations then&gt;</pre><p>Search range [0..9] is now cut into [0..4].</p><pre>Step 2:  n = 35  ;  digit = 0<br>    n ≥ 30<br>    n := n – 30  ;  digit := digit + 3</pre><p>Search range [0..4] is cut into [3..4].</p><pre>Step 3:  n = 5  ;  digit = 3<br>    n &lt; 10<br>    &lt;we don&#39;t make any alterations then&gt;</pre><p>So the proper value of the second digit is found to be ‘3’, and ’<em>n</em>’ is reduced from 2-digit number 35 into 1-digit number 5. Which is itself the last digit of original <em>n</em>=735, and can be printed just as it is.</p><p>If we try to graphically illustrate the diagram of searching proper digit in decimal positional system, we might come up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*w_13kSZ6SYqD0Y1QeH31fA.png" /><figcaption><em>Diagram of searching proper decimal digit, acting as in Binary search.<br>The digit portions [5, 3, 2, 1] are represented from top to bottom, as jumps of different length.<br>Combining various digit portions, we are able to sum up any digit.</em></figcaption></figure><p>So we see that for every digit, we can iterate by amounts [5, 3, 2, and 1], in order to obtain value of that digit. I prefer to call those amounts “digit portions”, as their different subsets are capable of summing-up the values of all decimal digits. And while considering every digit portion, we do 1 multiplication, 1 comparison, and possibly 1 subtraction.</p><p>Having this said, we can write the pseudo-code for described algorithm:</p><pre>var powers_of_10[0 .. 10] : Array of Integers <br>        = { 1, 10, 100, 1&#39;000, ..., 100&#39;000&#39;000, 1&#39;000&#39;000&#39;000 }<br>        // Precalculated powers of 10, which will be used during print<br><br>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into the &#39;result&#39; array.<br>procedure print( N: Integer )<br>    L := calculate_digits_count( N )<br>    i := 0  // Index over the &#39;result&#39; array<br>    while L &gt; 0<br>        digit := 0  // Start summing up current digit from 0<br>        // Iterate over digit portions with &#39;p&#39; variable<br>        for p in [5, 3, 2, 1]<br>            term := p * powers_of_10[ L-1 ]<br>            if N &gt;= term  // we should use digit portion &#39;p&#39;<br>                digit :=  digit + p  // Increase current digit<br>                N := N – term  // ... and reduce &#39;N&#39; accordingly<br>        result[ i ] := &#39;0&#39; + digit   // Write the digit into &#39;result&#39; array<br>        i := i+1  // Prepare to next iteration, and<br>        L := L-1  // ... adjust remaining count of digits of &#39;N&#39;<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character</pre><p>As my algorithm is based on building up digits values with help of digit portions, I prefer to call it “Digit Portions printer”, or shortly “DP printer”.</p><p>Note, here we also rely on some function “calculate_digits_count()”, which returns the count of decimal digits of given number ’<em>n</em>’, so we can instantly start comparing ’<em>n</em>’ with proper power of 10. And similarly to the case of printing in binary notation, here also we can use the precalculated array of powers of 10, to quickly find out count of decimal digits of ‘<em>n</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*a_1pJBOHOCnEX5-bHVKfVA.png" /><figcaption>How <em>the count of digits L is being calculated for number N = 47&#39;024.<br>We sequentially compare N to powers of 10, until N becomes less.<br>That happens on power 100&#39;000 which is 10⁵, so we conclude that L=5.</em></figcaption></figure><p>In the pseudo-code, only the precalculated array’s name and its largest index should be altered:</p><pre>// This function takes integer &#39;N&#39; and returns count of its decimal digits.<br>function calculate_digits_count( N: Integer ) : Integer;<br>    // Check case of numbers with maximal count of digits<br>    if N &gt;= powers_of_10[ 9 ]  // Compare with maximal power of 10<br>        return 10  // The count of digits for such numbers<br>    // Regular case<br>    L := 0<br>    while N &gt;= powers_of_10[ L ] <br>        L := L+1<br>    return L</pre><p>The presented 2 fragments of code together give us the complete algorithm for printing integers in decimal numeral system. The algorithm doesn’t make use of integer division or remainder calculation operations.</p><p>Let me note, that in contrast to printing in binary numeral system, here, if the number ’<em>n</em>’ being printed has the maximal count of decimal digits, some overflow issues might arise. For example, if working with 32-bit unsigned integers, which can represent range of values [0, 4&#39;294&#39;967&#39;296), and if the number being printed is “1&#39;500&#39;000&#39;000” (also having 10 decimal digits), then we must be careful not to compare it with “5 * 1&#39;000&#39;000&#39;000 = 5&#39;000&#39;000&#39;000”, as the last one just doesn’t fit in 32 bits. So there, the digit portion “5” must be skipped, only digit portions [3, 2, 1] should be considered for getting the first digit of ‘<em>n</em>’. After that, all the next digits should be obtained in the described way.</p><p>So adding one more condition to the pseudo-code, like “if n &gt;= 1&#39;000&#39;000&#39;000”, will be enough. I just decided to skip it, for compactness of the presented pseudo-codes.</p><h3>6. The algorithm for other positional numeral systems</h3><p>The presented algorithm “DP printer” can be easily adjusted for printing numbers in any other positional numeral system. The only difference will be that the sequence of digit portions [5, 3, 2, 1] is replaced by some other sequence of digit portions, and that when performing comparisons and subtractions, we should multiply every digit portion not by some power of 10, but some power of the new <em>base</em>.</p><p>For example, if we would like to print numbers in <em>base</em>=14, then possible sequence of digits portions might be like [7, 4, 2, 1].</p><p>Generally, when constructing digits portions for given numbers base, we should always try to cut the digits range into 2 equal (or almost equal) parts. That’s why for <em>base</em>=14 the preferred way is to first cut range [0..14) by digit portion ‘7’ into two sub-ranges [0..7) and [7..14), then cut each sub-range by digit portion ‘4’ into sub-ranges [0..4), [4..7), [7..11) and [11..14), and so on, until reaching sub-ranges of unit length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*VThB9irZIu-EXgoKJCaaIQ.png" /><figcaption><em>Diagram of searching proper decimal digit, when we are <br>in base=14, acting similarly to Binary search algorithm.<br>The digit portions [7, 4, 2, 1] are represented from top to bottom, <br>as jumps of different length. Combining various digit portions, <br>we are able to sum-up any value (digit) in range [0..13].</em></figcaption></figure><p>If writing pseudo-code for printing routine in the new base 14, the only differences would be:</p><ul><li>replacing digit portions sequence [5, 3, 2, 1] by sequence [7, 4, 2, 1], corresponding to the base 14, and</li><li>replacing precalculated powers of 10 by precalculated powers of 14.</li></ul><h3><strong>7. Necessary optimizations</strong></h3><p>We have presented the basic version of the new integer printing algorithm “DP printer”. However, if we run it along with the standard conversion algorithm and compare their performances, we will see that the standard one works faster. That’s why in this chapter I will present several sequential optimizations, which can (and should) be applied to the basic version of “DP printer”, in order to make it to outperform all existing solutions.</p><h4><em>Optimization A: loop unrolling</em></h4><p>We can easily note that if we are in a certain numbers base (right now, in <em>base</em>=10), digit portions become predefined (like [5, 3, 2, 1]), so we have the option of unrolling the inner loop, thus reaching some speed-up:</p><pre>var powers_of_10[0 .. 10] : Array of Integers <br>        = { 1, 10, 100, 1&#39;000, ..., 100&#39;000&#39;000, 1&#39;000&#39;000&#39;000 }<br>        // Precalculated powers of 10, which will be used during print<br><br>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into the &#39;result&#39; array.<br>procedure print( N: Integer )<br>    L := calculate_digits_count( N )<br>    i := 0  // Index over the &#39;result&#39; array<br>    while L &gt; 0<br>        digit := 0  // Start summing-up current digit from 0<br>        // Go over digit portions:<br>        //     digit portion &#39;5&#39;<br>        term := 5 * powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;5&#39;<br>            digit :=  digit + 5  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>        //     digit portion &#39;3&#39;<br>        term := 3 * powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;3&#39;<br>            digit :=  digit + 3  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>        //     digit portion &#39;2&#39;<br>        term := 2 * powers_of_10[ L-1 ]<br>        if N &gt;= term<br>            digit :=  digit + 2<br>            N := N – term<br>        //     digit portion &#39;1&#39;<br>        term := powers_of_10[ L-1 ]<br>        if N &gt;= term<br>            digit :=  digit + 1<br>            N := N – term<br>        // Write produced digit into &#39;result&#39; array<br>        result[ i ] := &#39;0&#39; + digit<br>        i := i+1  // Prepare to next iteration, and<br>        L := L-1  // ... adjust remaining count of digits of &#39;N&#39;<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character</pre><p>Unrolling the inner loop in this way will take out 4 checks and 4 index increments of the “for” loop.</p><p>Experimental comparisons presented later in chapter 8, will show that such unrolling has a significant positive impact on the performance.</p><h4><em>Optimization B: reducing number of multiplications</em></h4><p>According to “DP printer”, in order to obtain value of every digit we multiply digit portions [5, 3, 2, 1] by the current power of 10. So for example, for obtaining the digit of “thousands” (4&#39;th from right), we are doing the following multiplications:</p><blockquote>5*1&#39;000<br>3*1&#39;000<br>2*1&#39;000<br>1*1&#39;000 (this is actually skipped, as is multiplied by 1)</blockquote><p>after which obtained values are being compared and possibly subtracted from ‘<em>n</em>’.</p><p>We were doing that because our purpose was to cover range of possible digits [0..9] with some decreasing sequence of digit portions. But what if we violate the logic of binary search a bit, and come up with a slightly different sequence of digit portions? Such a sequence, which will reduce overall number of multiplications that we should do.</p><p>For example, if instead of sequence of digit portions [5, 3, 2, 1] we take another sequence [3,3,1,1,1], we will still cover the required range of digits [0..9]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*B5KFd7XfU-9snLcKD210wg.png" /><figcaption><em>The altered sequence of digit portions [3,3,1,1,1]. <br>The first 2 portions are illustrated as large jumps of length 3, <br>while the remaining 3 portions are represented with small jumps of length 1.<br>Here also, by combining various portions, we are able to sum up any digit <br>in necessary range [0..9].</em></figcaption></figure><p>For computing corresponding terms with this new sequence of digits portions, we will do less multiplications:</p><blockquote>3*1&#39;000<br>3*1&#39;000 (this is repeating, so is skipped)<br>1*1&#39;000 (this is actually skipped, as multiplied by 1)<br>1*1&#39;000 (as well as the remaining 2 repeating terms)<br>1*1&#39;000 (…)</blockquote><p>So we see that sequence of digits portions [3,3,1,1,1] allows us to make only one multiplication per digit, compared to three multiplications per digit of the previous digit portions [5,3,2,1].</p><p>After this optimization, pseudo-code becomes like this:</p><pre>var powers_of_10[0 .. 10] : Array of Integers <br>        = { 1, 10, 100, 1&#39;000, ..., 100&#39;000&#39;000, 1&#39;000&#39;000&#39;000 }<br>        // Precalculated powers of 10, which will be used during print<br><br>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into the &#39;result&#39; array.<br>procedure print( N: Integer )<br>    L := calculate_digits_count( N )<br>    i := 0  // Index over the &#39;result&#39; array<br>    while L &gt; 0<br>        digit := 0  // Start summing-up current digit from 0<br>        // Go over digit portions:<br>        //     digit portion &#39;3&#39;<br>        term := 3 * powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;3&#39;<br>            digit :=  digit + 3  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>        //     one more digit portion &#39;3&#39;, (&#39;term&#39; remains same)<br>        if N &gt;= term<br>            digit :=  digit + 3<br>            N := N – term<br>        //     digit portion &#39;1&#39;<br>        term := powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;1&#39;<br>            digit :=  digit + 1  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>        //     one more digit portion &#39;1&#39; (&#39;term&#39; remains same)<br>        if N &gt;= term<br>            digit :=  digit + 1<br>            N := N – term<br>        //     one more digit portion &#39;1&#39; (&#39;term&#39; remains same)<br>        if N &gt;= term<br>            digit :=  digit + 1<br>            N := N – term<br>        // Write produced digit into &#39;result&#39; array<br>        result[ i ] := &#39;0&#39; + digit<br>        i := i+1  // Prepare to next iteration, and<br>        L := L-1  // ... adjust remaining count of digits of &#39;N&#39;<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character</pre><p>You might argue that the count of digit portions has increased now from 4 to 5, and so it might slow down the algorithm. Yes, it could be the case, but this change is required for the next optimization, which will justify the current one.</p><h4><em>Optimization C: skipping repeated portions, which didn’t work before</em></h4><p>Let’s assume that we decided to print input number ’<em>n</em>’ by digit portions [3,3,1,1,1]. Also let’s assume that we are currently on “thousand”-s digit (4&#39;th from right). Following that logic we will first try to reduce ’<em>n</em>’ by 3&#39;000. If that works we will try to reduce ’<em>n</em>’ by 3&#39;000 once again. After that, we will 3 times compare the remaining ’<em>n</em>’ with 1&#39;000, and similarly try to reduce it by 1&#39;000.</p><p>But if at the first step ’<em>n</em>’ was less than 3&#39;000, then no subtraction will be made, and ’<em>n</em>’ will remain unchanged. And despite that, in the next step we will compare it with 3&#39;000 again, which is pointless. If digit portion is repeated, it makes sense to analyze it only if the previous comparison worked, in other words, if ’<em>n</em>’ was reduced by it.</p><p>Having this noted, we can nest our conditions, which will result in the following pseudo-code:</p><pre>var powers_of_10[0 .. 10] : Array of Integers <br>        = { 1, 10, 100, 1&#39;000, ..., 100&#39;000&#39;000, 1&#39;000&#39;000&#39;000 }<br>        // Precalculated powers of 10, which will be used during print<br><br>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into the &#39;result&#39; array.<br>procedure print( N: Integer )<br>    L := calculate_digits_count( N )<br>    i := 0  // Index over the &#39;result&#39; array<br>    while L &gt; 0<br>        digit := 0  // Start summing-up current digit from 0<br>        // Go over digit portions:<br>        //     digit portion &#39;3&#39;<br>        term := 3 * powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;3&#39;<br>            digit :=  digit + 3  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>            //     one more digit portion &#39;3&#39; (&#39;term&#39; remains same)<br>            if N &gt;= term<br>                digit :=  digit + 3<br>                N := N – term<br>        //     digit portion &#39;1&#39;<br>        term := powers_of_10[ L-1 ]<br>        if N &gt;= term  // we should use digit portion &#39;1&#39;<br>            digit :=  digit + 1  // Increase current digit<br>            N := N – term  // ... and reduce &#39;N&#39; accordingly<br>            //     one more digit portion &#39;1&#39; (&#39;term&#39; remains same)<br>            if N &gt;= term<br>                digit :=  digit + 1<br>                N := N – term<br>                //     one more digit portion &#39;1&#39;<br>                if N &gt;= term<br>                    digit :=  digit + 1<br>                    N := N – term<br>        // Write produced digit into &#39;result&#39; array<br>        result[ i ] := &#39;0&#39; + digit<br>        i := i+1  // Prepare to next iteration, and<br>        L := L-1  // ... adjust remaining count of digits of &#39;N&#39;<br>    result[ i ] := &#39;\0&#39; </pre><p>Obviously, this will have its speed up when calculating the value of current digit. For example, if current digit is actually ‘1’, only the 1st, 3rd, and 4th digit portions will be analyzed ([3,_,1,1,_]). Or if current digit is ‘6’, only 1st, 2nd and 3rd digits portions will be analyzed ([3,3,1,_,_]). While surely, for some other digits there will be no performance gain. For example if current digit is ‘9’, the algorithm will still do all the comparisons ([3,3,1,1,1]), as the value “9” should be “decremented” more times, than values “1” or “6”.</p><h4><em>Optimization D: moving from base=10 to base=100</em></h4><p>Within the previous 3 optimizations A, B, and C, we cover range of possible digits [0..9] by some sequence of digit portions, which are later being used to obtain value of every digit of ’<em>n</em>’. But what if instead we will try to cover range of all possible 2 adjacent digits [00..99] by another sequence of digit portions (this time, more proper will be to say digits-pair portions), and later use them to obtain values of 2 adjacent digits of ’<em>n</em>’ during a single step? Surely we have no guarantee that it will work faster, but nothing prevents us from trying.</p><p>Within my experiments I tried the following two sequences of digits-pair portions:</p><blockquote>a) [33,33,11,11,4,4,1,1,1]<br>b) [20,20,20,20,4,4,4,4,1,1,1]</blockquote><p>Note, they both cover the range [00..99], which corresponds to two adjacent digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*W0gJzZczw7VLYk9iyr0k9g.png" /><figcaption><em>Sequence of digits-pair portions [33,33,11,11,4,4,1,1,1]. <br>The first 2 portions are illustrated as large jumps of length 33.<br>The next 2 portions are illustrated as smaller jumps of length 11.<br>Next 2 portions are represented with smallest arrows of length 4.<br>The last portions of “1” are not illustrated.</em></figcaption></figure><p>Within this optimization we will still apply similar comparisons and subtractions on the input number ’<em>n</em>’, but now, after every iteration we will obtain values of 2 adjacent digits, having summed up in another variable “digits_pair”, which will result in something between [0..99]. Then, in order to be able to efficiently print those 2 digits, we should also have prepared an array of length 100, which will map indexes from 0 to 99, to corresponding pairs of characters (from “00”, “01”, “02”, … to … “98”, “99”).</p><p>Important notes: here we still have repeated portions, which allows us to use also optimizations B and C. And as it was for the base version of “DP printer”, as the count of digits of ’<em>n</em>’ might be the maximal, here also we must be careful to choose only such digits-pair portions which will not cause overflows, when multiplied by necessary powers of 100.</p><p>Experimental results, presented in the next chapter, show that this optimization actually brings its own speed-up.</p><h3>8. Experimental results</h3><p>Of course, a suggestion of any optimization should be backed up by experimental comparison. In this chapter, I want to present comparisons of runtimes of the following integer printing algorithms:</p><ul><li>Standard printer with first optimization [Std],</li><li>Standard printer with first &amp; second optimizations as [Std 2-dig],</li><li>LR printer [LR],</li><li>LR printer with second optimization as [LR 2-dig],</li><li>DP printer [DP] (chapter 5),</li><li>DP printer with optimization A as [DP A] (loop unrolling, chapter 7),</li><li>DP printer with optimizations A and B as [DP AB] (repeated digit portions),</li><li>DP printer with optimizations A, B and C as [DP ABC] (nesting conditions),</li><li>DP printers with all 4 described optimizations (chapter 7):<br> … with digits-pair portions [33,33,11,11,4,4,1,1,1] as [DP A-D 33],<br> … with digits-pair portions [20,20,20,20,4,4,4,4,1,1,1] as [DP A-D 20].</li></ul><p>All the listed algorithms were printing numbers in <em>base</em>=10, however we can easily change that for any other base, if required.</p><p>The experiments were performed separately, on the following types of integers:</p><ul><li>32-bit integers, 5 decimal digits,</li><li>32-bit integers, 8 decimal digits,</li><li>64-bit integers, 8 decimal digits,</li><li>64-bit integers, 18 decimal digits.</li></ul><p>As the printing algorithm currently used in standard libraries of most programming languages is the “Standard algorithm” with the first optimization enabled (chapter 3), here I will present performance gain of every other algorithm in relation to the former.</p><h4><em>Comparison results for 32-bit integers</em></h4><p>Comparing running times when converting 32-bit integers to strings gives the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMPLdImsURSD-6V3uwc3uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qk59noO1WBpMwLs6UmsS1g.png" /><figcaption><em>Average time (in nanoseconds) required to print one 32-bit integer, <br>having either 5 or 8 decimal digits, by every of the listed algorithms.</em></figcaption></figure><p>We can see that the basic version of DP printer [DP] (without optimizations) performs by around 23% slower than current standard algorithm [Std].</p><p>However, once we enable optimization A (loop unrolling) [DP A] it starts to behave around <strong>29–32%</strong> faster.</p><p>Turning on the optimization B (introducing repeated digit portions) [DP AB] drops down the performance gain, making it only about 18–22% faster. Probably that is because we are taking now 5 digit portions, instead of 4.</p><p>But enabling the optimization C too (eliminating checks for repeated portions) [DP ABC] brings even more performance gain: making it around <strong>43–45%</strong> faster than the standard routine.</p><p>When enabling all 4 optimizations we have 2 cases: [DP A-D 33], and [DP A-D 20]. Exact digits-pair portions are specified at the beginning of this chapter. For printer [DP A-D 33] we have <strong>34–49%</strong> performance gain compared to [Std], and for [DP A-D 20] is makes around <strong>47–59%</strong> faster than currently standard printing algorithm.</p><p>The title of this story was chosen based on results of comparing printer [DP ABC] with the currently standard printing algorithm [Std], for 32-bit integers case. This has 2 reasons:</p><ul><li>[DP ABC] is the most optimized variant which still doesn’t use the 2-digits table. I think, as the currently standard algorithm also doesn’t use any tables, it will be fair to compare it with the one which doesn’t require them either.</li><li>Among integers, 32-bit integer is the most commonly used data type.</li></ul><p>So taking the “32-bit / 8 digits” case, and dividing the runtime of [Std] over the one of [DP ABC] (from the table above), we get:</p><blockquote>19.77 / 10.76 ≈ 1.84</blockquote><h4><em>Comparison results for 64-bit integers</em></h4><p>Comparison results of printing 64-bit integers are even more impressive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxi6GWNRhgFz6pR7DHl33w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyDn8_qRkaPNOR4_d56oSw.png" /><figcaption><em>Average time (in nanoseconds) required to print one 64-bit integer, <br>having either 8 or 18 decimal digits, by every of the listed algorithms.</em></figcaption></figure><p>Here we can see that the basic version of DP printer [DP] now doesn’t drop performance, compared to the standard algorithm [Std], as it was for the 32-bit case. Instead it brings around <strong>26%</strong> performance gain.</p><p>Enabling optimization A (unrolling the inner loop) [DP A] makes it <strong>50–52%</strong> faster.</p><p>Similarly to the 32-bit integers case, here also turning on optimization B (introducing repeated digit portions) [DP AB] drops down performance gain, making it only 40–44% faster from [Std].</p><p>But enabling optimization C too (eliminating checks for repeated portions) [DP ABC] makes the algorithm <strong>57–62%</strong> faster.</p><p>Enabling all 4 optimizations for the 64-bit integers case [DP A-D 33] and [DP A-D 20] makes the algorithm behave around <strong>68–72%</strong> faster, compared to the currently standard printing algorithm [Std].</p><p>Note, if for the 64-bit integers case we would perform the same comparison of efficiencies between [DP ABC] and [Std] (the printers which don’t use internal tables), as we did for the 32-bit integers a bit above, we would get:</p><blockquote>72 / 27.7 ≈ 2.6</blockquote><p>which is significantly higher than the 1.8 ratio of 32-bit case.</p><h3>9. Conclusion</h3><p>We have presented a new algorithm “DP printer” for converting integers to strings. It does not rely on the relatively time-consuming arithmetical operations, such as integer division or remainder calculation. Instead, “DP printer” uses only multiplication, comparison, and subtraction.</p><p>The algorithm can be significantly optimized if the base in which numbers should be printed is known at compile time. That will allow to unroll the inner loop right in the code, and to make the subsequent optimizations B, C and D, all as described in chapter 7. Note, this requirement is almost always satisfied, as numbers are generally printed in <em>base</em>=10. And if not, the base is still often known at compile-time, like when printing numbers in octal (<em>base</em>=8) or hexadecimal (<em>base</em>=16) numeral systems.</p><p>If number base is not known at the compile time, the algorithm still works without doing any time-consuming operation, but its performance gain is either small (as for 64-bit case) or absent (for 32-bit case).</p><p>Experiments show that the optimized version of my algorithm performs around <strong>43–45% faster</strong> for printing 32-bit integers, and around <strong>57–62% faster</strong> for 64-bit integers. Performance gain of “DP printer” compared to the standard printing algorithm is expected to be significantly higher when working with big integers (objects capable of storing unlimited count of digits, thus representing values greater than 64-bit integers).</p><p>Converting integers to their string representation is never a bottleneck in most computer programs, as generally, only tiny percent of calculated integers is being sent for printing. However, if the program generates large text files (like *.json or *.csv), then the count of printed integers can be quite large, and the performance of integer to string conversion algorithm starts playing role.</p><p>That’s all for now! Thank you for reading my story till the end. I will be happy to read any of your thoughts and comments below!</p><blockquote>Great thanks to David Ayrapetyan for precise and careful review of the draft of this story! ( <a href="https://www.linkedin.com/in/davidayrapetyan/">https://www.linkedin.com/in/davidayrapetyan/</a> )</blockquote><blockquote>If you enjoyed reading, you can find and connect to me on LinkedIn ( <a href="https://www.linkedin.com/in/tigran-hayrapetyan-cs/">https://www.linkedin.com/in/tigran-hayrapetyan-cs/</a> )</blockquote><h3>References:</h3><p>[1] : “Integer to string conversion” — <a href="https://tia.mat.br/posts/2014/06/23/integer_to_string_conversion.html">https://tia.mat.br/posts/2014/06/23/integer_to_string_conversion.html</a></p><p>[2] : “Three optimization tips for C++” — <a href="https://www.facebook.com/notes/10158791579037200/">https://www.facebook.com/notes/10158791579037200/</a></p><p>[3] : “34% Faster Integer to String Conversion Algorithm” — <a href="https://medium.com/towards-data-science/34-faster-integer-to-string-conversion-algorithm-c72453d25352">https://medium.com/towards-data-science/34-faster-integer-to-string-conversion-algorithm-c72453d25352</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52d43bd265e0" width="1" height="1" alt=""><hr><p><a href="https://www.cantorsparadise.com/1-8x-faster-integer-printing-algorithm-52d43bd265e0">1.8x faster Integer printing algorithm</a> was originally published in <a href="https://www.cantorsparadise.com/">Cantor’s Paradise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[34% faster Integer to String conversion algorithm]]></title>
            <link>https://medium.com/data-science/34-faster-integer-to-string-conversion-algorithm-c72453d25352?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c72453d25352</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 22:20:02 GMT</pubDate>
            <atom:updated>2026-03-10T16:29:21.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>34% Faster Integer to String Conversion Algorithm</h3><h4><em>Are we printing integers fast enough?</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*KJVEk-Q0FJQOKmZnDllAwA.png" /></figure><h3>1. Introduction</h3><p>In computer programming, converting given integer to a string is a common operation, which should be done for example before printing the integer to the screen, or printing it to any kind of textual file, such as *.xml, *.json, *.csv, *.txt, etc…</p><p>It is well known that integers (as well as everything else) are stored in computer memory in binary format — as sequences of 0s and 1s. For example:</p><ul><li>number 12 is represented in memory as “1100”,</li><li>and number 29 is represented as “11101”.</li></ul><p>This is the reason why such a conversion is needed every time, when we want to bring it into human-readable, decimal format.</p><p>In this story I am going to:</p><ul><li>make an overview of the standard algorithm used for such conversion,</li><li>observe its existing optimizations,</li><li>propose my algorithm, and</li><li>present their experimental comparison.</li></ul><p>We will see that on average, my algorithm runs <strong>25–38%</strong> faster for 32-bit integers, and <strong>40–58%</strong> faster for 64-bit integers, than the optimized standard algorithm. Its implementation in C++ language can be found on GitHub, as referenced at the end.</p><p>Of course, if the application prints only a few integers during its lifetime, the algorithm which is responsible for converting them to strings will never be the bottleneck. But for cases when the application prints tons of data into text files, the efficiency of the converting algorithm starts playing role. When working in fields such as Data Science or Machine Learning, the need for converting lots of integers into strings arises e.g. when exporting a dataset into a text file, such as *.csv or *.json.</p><h3>2. The standard conversion algorithm</h3><p>As converting integers to strings is a common operation, an algorithm for that is implemented in any modern programming language, either as part of the language itself or as part of its standard library. And the algorithm is almost everywhere the same — the one which is based on repeatedly obtaining and picking out the last digit of the integer, and continuing with its remaining part.</p><p>In order to obtain the last digit of given integer <em>N</em>, it just calculates the remainder of its division upon 10:</p><blockquote>“digit := N mod 10”,</blockquote><p>and in order to pick it out, it performs the integer division itself:</p><blockquote>“N := N / 10”.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*wYJpUw9XNYdAgLgRwp1TuA.png" /><figcaption><em>Given an integer N, how its last digit <br>and the remaining part are being computed.</em></figcaption></figure><p>Note, in this story, when dividing 2 integers, we will assume that only the whole part of result is taken.</p><p>As an example of complete algorithm, when printing number “<em>N</em> = 2&#39;167”, the following operations will be made:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*9JV3Ozp6TyRpvJPM6Z5DGg.png" /><figcaption><em>Operations for printing number “2167”:<br>Step 1: 2167 % 10 = 7 (storing digit “7”) , 2167 / 10 = 216 (continuing with 216),<br>Step 2: 216 % 10 = 6 (storing digit “6”) , 216 / 10 = 21 (continuing with 21),<br>Step 3: 21 % 10 = 1 (storing digit “1”) , 21 / 10 = 2 (continuing with 2),<br>Step 4: As “2 &lt; 10”, just storing the last digit “2”.<br>Step 5: (not illustrated) reversing order of stored digits and printing them.</em></figcaption></figure><p>Note, when we are dealing with 1-digit integer (i.e. from range [0..9]), we can directly send it for print, as corresponding characters are already fixed for each of those 10 digits. And a remainder of division upon 10 is always 1-digit integer.</p><p>Also we can note that this algorithm reports digits of <em>N</em> in reverse order (here we got sequence of digits ‘7’, ‘6’, ‘1’, ‘2’, instead of having ‘2’, ‘1’, ‘6’, ‘7’), so there is need to reverse the produced sequence at the end.</p><p>Summarizing that, its pseudo-code will be like this:</p><pre>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into &#39;result&#39; array.<br>procedure print( N: Integer )<br>    i := 0  // Index over &#39;result&#39; array<br>    while N &gt; 0<br>        result[ i ] := &#39;0&#39; + (N mod 10)  // Take the last digit<br>        N := ⌊ N / 10 ⌋   // Pick out the last digit<br>        i := i+1<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character<br>    reverse array result[0 .. i-1]</pre><p>The described algorithm is simple, and we can easily implement it in 3–4 lines of code. But its bottleneck is that it uses 2 relatively expensive operations — integer division and integer remainder calculation, for every digit of <em>N</em>’s decimal notation. It is well known that integer division and remainder calculation on average take 4–5 times longer, than addition, subtraction or even multiplication of 2 integers. Here we can observe time benchmarking of mentioned arithmetical operations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8ESpzP1CUPUjGtqrDRyxA.png" /><figcaption><em>Experimental comparison of time (in nanoseconds) spent to perform the 5 types of <br>arithmetical operations (each operation is run 200 times on random data).<br>We can see that the last 2 operations (integer division and remainder calculation)<br>are taking significantly more time. Also, we see that integer multiplication <br>is performed almost as fast as addition or subtraction.</em></figcaption></figure><p>The experiments were made with Google Benchmark, under the following system:</p><p><em>CPU: Intel Core i7–11800H @ 2.30GHz<br>RAM: 16.0 GB<br>OS: Windows 11 Home, 64-bit<br>Compiler: MSVC 2022 ( /O2 /Ob2 /MD /GR /Gd )</em></p><p>Let’s see if faster methods for integer printing exist…</p><h3>3. Existing optimizations</h3><h4>Optimization 1</h4><p>One common optimization for the described algorithm is in eliminating the last step of reversing produced sequence of digits. The trick is well presented for example in [1]. Within this optimization we will write digits in the buffer straightaway in their proper order. And as the algorithm itself reports digits of given integer <em>N</em> from right to left, so we also will write them in the buffer from right to left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*tnJ-HT_4eSBTwV8KZtIliA.png" /><figcaption><em>Filling produced digits into result array from right to left,<br>directly in the order they should have at the end.</em></figcaption></figure><p>Pseudo-code with this optimization will look as follows:</p><pre>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The function takes integer &#39;N&#39; to be printed, and returns position <br>// of its converted first character in the &#39;result&#39; array.<br>function print( N: Integer ) : Integer<br>    result[ 25 ] := &#39;\0&#39;  // Place the terminating &#39;null&#39; character at the end<br>    i := 25  // Index over &#39;result&#39; array<br>    while N &gt; 0<br>        i := i-1  // Here we go to left, for placing the next digit<br>        result[ i ] := &#39;0&#39; + (N mod 10)  // Take the last digit<br>        N := ⌊ N / 10 ⌋  // Pick out the last digit<br>    return i  // Position from where the converted integer starts</pre><p><em>Note, in this and all other pseudo-codes within this story we are not handling the case of printing number “0”. According to all written algorithms, “0” will result as a sequence with no digits at all, and that is why in almost all printing algorithms, printing “0” is made in a separate branch. We will just skip that branch here for compactness.</em></p><p>Another small advantage of this optimization is that we are not required to write the terminating null-character after every conversion. Instead, we can write it only once in the last position of the buffer, as physically position of <em>N</em>’s last digit is fixed in advance, and it will always be the one-before-last position in the buffer.</p><p>The drawback of this optimization is that the position of the first character becomes variable, as it becomes dependent on number of digits that integer <em>N</em> has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*PDIPGMh24T8KgkRC_w40HA.png" /><figcaption><em>Drawback of optimization 1: numbers with different <br>digits count will start in the output array from different positions.</em></figcaption></figure><p>However, practically, this does not become a problem, because the converted integers are often promptly sent to a text file or to the screen, thus not remaining in memory for long. And for such purposes we do not need for the converted digits to be written starting from some exactly in advance specified position of the memory.</p><h4>Optimization 2</h4><p>Next optimization is about using integer division and remainder calculation operations to obtain 2 digits of <em>N</em> in a single step. This trick is also well documented in [1] and [2]. For this purpose, instead of repeatedly calculating</p><blockquote>“digit := N mod 10”, followed by<br>“N := N / 10”,</blockquote><p>we will calculate:</p><blockquote>“digits := N mod 100”, followed by<br>“N := N / 100”,</blockquote><p>which will give us the last 2 digits of <em>N</em>, and then will cut them both off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*jGIL8EzLippLMJRTXoG52g.png" /><figcaption><em>Operations for printing number “5174092” with second optimization enabled:<br>Step 1: 5174092 % 100 = 92 (storing digits “92”) , 5174092 / 100 = 51740 (continuing with 51740),<br>Step 2: 51740 % 100 = 40 (storing digits “40”) , 51740 / 100 = 517 (continuing with 517),<br>Step 3: 517 % 100 = 17 (storing digits “17”) , 517 / 100 = 5 (continuing with 5),<br>Step 4: As “5 &lt; 100”, just storing the last digit “5”.</em></figcaption></figure><p>Note, in order to eventually and efficiently print those obtained 2 digits, here we should have prepared an array of length 100 (with indexes from 0 to 99 — thus corresponding to all possible remainders “<em>N</em> mod 100”), where values will be pairs of characters, starting from “00”, “01”, “02”, … till “98”, “99”.</p><p>Within this optimization, count of integer division and remainder operations is reduced by almost 2 times.</p><p>Finalizing this part, I want to grab your attention to the fact that even with the described both optimizations enabled, we still do number of integer division and remainder calculation operations, proportional to the count of digits in given integer <em>N</em>.</p><h3>4. My algorithm</h3><p>I am going to propose another algorithm, which will accelerate integer printing by around <strong>25–38%</strong> for 32-bit integers, and around <strong>40–58%</strong> for 64-bit integers. The idea is — what if we pick digits out of given integer <em>N</em> not from right to left, but from left to right? So at first we will obtain its most significant digit, then the next significant digit, and so on, until only the least significant digit remains. Doing this becomes a bit difficult if we don’t know the count of digits of <em>N</em> in advance, but let us put that question aside for now, and assume that we already know that there are <em>L</em> digits in <em>N</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*NMgyP-mU_fMQQf0z3YfNTw.png" /><figcaption><em>Example of an input number N which has L=7 digits.</em></figcaption></figure><p>How are we going to obtain the most significant digit then? Again using integer division, but this time as:</p><blockquote>“digit := N / 10^(L-1)”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*3oLlHvgElJ7aMEvGWyvN5w.png" /><figcaption><em>Examples of obtaining left-most digits of given integers.</em></figcaption></figure><p>And how are we going to pick it out of <em>N</em>, in order to be able to continue with the remaining part? After knowing the value of the most significant digit is ‘<em>d</em>’, we can do the following subtraction:</p><blockquote>“N := N — d*10^(L-1)”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*vmFvY_0Ny5W-DYs5REkhXQ.png" /><figcaption><em>Examples of picking left-most digits out of given integers.</em></figcaption></figure><p>Later we will repeat the division and subtraction operations, until <em>N</em> will become 1-digit integer (i.e. in range [0..9]), and finally will print that digit too. Let us view how the algorithm will work for case “<em>N</em> = 6&#39;129”. Note, it has 4 digits, so here we start with “<em>L</em>=4”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*BeQa1THUQN-gyDG1K_83GA.png" /><figcaption><em>Operations for printing number “6129” with my algorithm:<br>Step 1: 6129 / 1000 = 6 (printing digit ‘6’) , 6129–6*1000 = 129 (continuing with 129),<br>Step 2: 129 / 100 = 1 (printing digit ‘1’) , 129–1*100 = 29 (continuing with 29),<br>Step 3: 29 / 10 = 2 (printing digit ‘2’) , 29–2*10 = 9 (continuing with 9),<br>Step 4: As “9 &lt; 10” just printing the last digit ‘9’.</em></figcaption></figure><p>You might argue that calculating different powers of 10 is more time consuming than doing integer division or remainder calculation. And that will be absolutely correct except for one detail: we can precalculate all necessary powers of 10 and use them during program’s entire execution. For 32-bit integers, there are only 10 different powers of 10, and for 64-bit integers, there are 20 powers of 10. So keeping them all precalculated in memory will not be an issue.</p><p>So what do we have in overall? In order to print one digit of <em>N</em> with my algorithm we do:</p><blockquote>1 integer division,<br>1 multiplication, and<br>1 subtraction,</blockquote><p>compared to standard algorithm’s:</p><blockquote>1 remainder calculation and<br>1 integer division.</blockquote><p>In the next section we will see that my approach is actually better, because multiplication and subtraction together take less CPU time than remainder calculation. Experimental comparison of time-consumption of those arithmetical operations was presented in chapter 2.</p><p>Pseudo-code of the main part of my algorithm might look like this:</p><pre>var powers_of_10[0 .. 10] : Array of Integers <br>  = { 1, 10, 100, 1&#39;000, ..., 100&#39;000&#39;000, 1&#39;000&#39;000&#39;000 }<br>  // Precalculated powers of 10, which will be used during print<br><br>var result[0 .. 25] : Array of Characters  // Assume at most 25 characters<br><br>// The procedure takes integer &#39;N&#39; to be printed, and fills its<br>// decimal characters into the &#39;result&#39; array.<br>procedure print( N: Integer )<br>    L := calculate_digits_count( N )<br>    i := 0  // Index over &#39;result&#39; array<br>    while L &gt; 0<br>        digit := ⌊ N / powers_of_10[ L-1 ] ⌋  // Obtain left-most digit<br>        result[ i ] := &#39;0&#39; + digit   // Write it to the &#39;result&#39; array<br>        N := N – digit * powers_of_10[ L-1 ]  // Calculate remaining part<br>        L := L-1  // Adjust its count of digits accordingly<br>        i := i+1<br>    result[ i ] := &#39;\0&#39;  // Append the terminating &#39;null&#39; character</pre><p>As my algorithm prints digits of <em>N</em> from left to right, I want to call it “Left-to-right printer” or shortly “LR printer”.</p><p>The one thing which remains yet is to efficiently find <em>L</em> — count of decimal digits of <em>N</em>. And luckily for us, the precalculated array of powers of 10 will help here too. We can just iterate over that array from small powers to the larger ones, until finding such power 10^<em>L</em> which will be greater than <em>N</em>. Then the exponent <em>L</em> will itself represent the count of digits in <em>N</em>.</p><p>For example, obtaining count of digits for “<em>N</em> = 23&#39;504” will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*rYtllnznpbqUh9EpnQubNQ.png" /><figcaption><em>How the count of digits L is being calculated for number N = 23&#39;504.<br>We sequentially compare N to powers of 10, until N becomes less.<br>That happens on power 100&#39;000 which is 10⁵, so we conclude that L=5.</em></figcaption></figure><p>Pseudo-code of that function might look like:</p><pre>// The function takes integer &#39;N&#39; and returns count of its digits.<br>function calculate_digits_count( N: Integer ) : Integer<br>    // Check case of numbers with maximal count of digits<br>    if N &gt;= powers_of_10[ 9 ]  // Compare with maximal power of 10<br>        return 10  // Count of digits for such numbers<br>    // Regular case<br>    L := 0<br>    while N &gt;= powers_of_10[ L ] <br>        L := L+1<br>    return L</pre><p>With this 2 parts we are providing complete algorithm for converting integers to strings.</p><p>Note, as “LR printer” reports digits of <em>N</em> from left to right, there is no need to do any reversing at the end. Also, in contrast to existing optimization 1, here we keep the ability of specifying if where in memory the first digit of converted <em>N</em> should be placed.</p><p>“LR printer” can be used for printing numbers in any base (not just base 10). For doing so, we will only need to replace the precalculated powers of 10 with precalculated powers of the new base.</p><p>Implementation of “LR printer” in C++ language can be found on GitHub at [3].</p><h4><em>Optimization 2 for “LR printer”</em></h4><p>My algorithm can be enhanced with the second optimization described in “Existing optimizations” section, and documented in [1] and [2]. If done, then instead of printing the given number by 1 digit at a step, we will print it by 2 digits at a single step.</p><p>Let’s see how it will run for example on number “<em>N</em> = 4&#39;610&#39;937”. Here <em>L</em>=7, and we start by dividing <em>N</em> over 10^(L-2)=10&#39;000 this time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*f--1RSE5D2KoEtOSLDAKxA.png" /><figcaption><em>Actions for printing number “4610937” with second optimization enabled for “LR printer”:<br>Step 1: 4610937 / 10⁵ = 46 (printing digits ‘46’) , 4610937–46*10⁵ = 10937 (continuing with number 10937),<br>Step 2: 10937 / 10³ = 10 (printing digits ‘10’) , 10937–10*10³ = 937 (continuing with number 937),<br>Step 3: 937 / 10 = 93 (printing digits ‘93’) , 937–93*10 = 7 (continuing with number 7),<br>Step 4: As “7 &lt; 100”, just printing the last digit ‘7’.</em></figcaption></figure><p>By enabling this, we will spend:</p><blockquote>1 integer division,<br>1 multiplication, and<br>1 subtraction,</blockquote><p>per 2 digits of the input number.</p><p>Here again, the digits will be obtained in their natural order — from left to right, so there is no need to reverse them at the end.</p><p>Implementation of “LR printer” with second optimization enabled can also be found on GitHub at [3].</p><h3>5. Experimental comparison with existing algorithms</h3><p>Doing experimental comparison is essential for this type of work, so in this chapter I will present results of comparison between the following integer-printing algorithms:</p><ul><li>the standard algorithm with first optimization (labeled as “Std”),</li><li>my algorithm “LR printer” (labeled as “LR”),</li><li>standard algorithm with second optimization too (labeled as “Std [2-dig]”), and</li><li>“LR printer” with second optimization (labeled as “LR [2-dig]”).</li></ul><p>Each of those algorithms is tested both on 32-bit and 64-bit integers, with different count of digits of the input numbers.</p><h4>Printing numbers in base=10:</h4><p>Results when printing in number <em>base</em>=10 (the ordinary case) are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aqymk8Bup7Z6BjMO0AmfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MScGZc-HYkmlxPANxeRoog.png" /><figcaption><em>Time (in nanoseconds) spent to print 1 number (either 32-bit or 64-bit), <br>having certain count of digits, with different algorithms.<br>Printing is done in base=10.</em></figcaption></figure><p>For 32-bit integers, we can see that the gain of “LR printer” compared to standard printer is around <strong>30–38%</strong>. The gain when printing with second optimization (printing 2 digits at single step) is lower — <strong>13–28%</strong>. This is totally expected, as overall we do only 2 or 4 steps in that case.</p><p>When it comes to printing 64-bit integers, performance of my algorithm is even better. “LR printer” runs around <strong>40–50%</strong> faster than the standard algorithm. And with second optimization enabled for both, “LR printer” performs <strong>47–58%</strong> faster.</p><p>Percentage in the title of this story was chosen by addressing the most regular case: when we are in <em>base</em>=10, working with 32-bit integers, and assuming they have many digits. For that case performance gain of “LR printer” over standard algorithm was 30–38%, so taking the average makes around 34%.</p><h4>Printing numbers in base=3:</h4><p>Let’s also see if the results will differ significantly when printing integers in another base. We will observe printing in number <em>base</em>=3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nVnALPKZ_2U9mAm0cS_qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GORbdMV14OwsHgfYEagu1Q.png" /><figcaption><em>Time (in nanoseconds) spent to print 1 number (either 32-bit or 64-bit), <br>having certain count of digits, with different algorithms.<br>Printing is done in base=3.</em></figcaption></figure><p>As we can see here, for 32-bit integers performance gain of “LR-printer” over the standard algorithm is around <strong>25–33%</strong>, which generally corresponds to the difference in performance of used arithmetical operations.</p><p>And for 64-bit integers performance gain of “LR-printer” is around <strong>50–55%</strong> for short numbers (8 digits), and <strong>27–30%</strong> for long numbers (36 digits).</p><h4><em>Overall remarks</em></h4><p>Generally, the base in which integers are printed doesn’t affect relative performance gain much, as the count of operations to be performed during print is proportional to the count of digits that the input numbers have, and not to the number of possible values that those digits might have.</p><p>Almost always it is the case that the greater the count of digits is, that more “LR-printer” (or “LR-printer [2-dig]” variation) will outperform the standard printing algorithm (or its “2-dig” variation). This is also clear, because the more digits we have, that less impact will have the out-of-loop instructions (like calling one function from another, or placing the null-terminating character).</p><p>And overall, when printing 64-bit integers, results are more impressive for both “LR-printer” and “LR-printer [2-dig]” variation.</p><p>Personally for me, those results as quite notable.</p><h3>6. Conclusion</h3><p>We have presented a new algorithm for converting integers to strings, and called it “LR printer”. It runs by <strong>25–38%</strong> faster for 32-bit integers, and <strong>40–58%</strong> faster for 64-bit integers, compared to the optimized standard conversion algorithm. Our algorithm can work in any number base (not only in ordinary base 10).</p><p>The algorithm which converts integers into strings is never a bottleneck for applications that print only a few numbers during their lifetime. But for other types of applications, which automatically generate text files such as *.csv, *xml or *.json, the efficiency of the conversion algorithm matters. This is especially the case if those text files are going to contain lots of numbers, as is the case when exporting large datasets.</p><p>Huge thanks for reading till the end! Will be glad to read any comments below!</p><blockquote>I express my gratitude to David Ayrapetyan (<a href="https://www.linkedin.com/in/davidayrapetyan/">https://www.linkedin.com/in/davidayrapetyan/</a>), for careful reviewing the draft of this story, and proposing multiple contextual enhancements and grammatical corrections.</blockquote><blockquote>Gratitude to Hayk Aslanyan (<a href="https://www.linkedin.com/in/haykaslanyan/">https://www.linkedin.com/in/haykaslanyan/</a>), for making technical review of the draft, and proposing other enhancements.</blockquote><blockquote>All images, unless otherwise noted, are designed upon request of the author.</blockquote><blockquote>If you enjoyed reading this story, you can find me on LinkedIn at: <a href="https://www.linkedin.com/in/tigran-hayrapetyan-88989b12/">https://www.linkedin.com/in/tigran-hayrapetyan-88989b12/</a></blockquote><h3>References</h3><p>[1] : “Integer to string conversion” — <a href="https://tia.mat.br/posts/2014/06/23/integer_to_string_conversion.html">https://tia.mat.br/posts/2014/06/23/integer_to_string_conversion.html</a></p><p>[2] : “Three optimization tips for C++” — <a href="https://www.facebook.com/notes/10158791579037200/">https://www.facebook.com/notes/10158791579037200/</a></p><p>[3] : “LR printer implementation in C++ language” — <a href="https://github.com/tigranh/lr_printer">https://github.com/tigranh/lr_printer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c72453d25352" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/34-faster-integer-to-string-conversion-algorithm-c72453d25352">34% faster Integer to String conversion algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why all known real numbers are actually countable]]></title>
            <link>https://www.cantorsparadise.com/why-all-known-real-numbers-are-actually-countable-f09e57f83f4d?source=rss-36e8a35f28b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f09e57f83f4d</guid>
            <category><![CDATA[countability]]></category>
            <category><![CDATA[real-numbers]]></category>
            <category><![CDATA[cantor]]></category>
            <dc:creator><![CDATA[Tigran Hayrapetyan]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 16:19:54 GMT</pubDate>
            <atom:updated>2023-10-21T16:19:54.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Illustration of correspondence between natural numbers and known real numbers" src="https://cdn-images-1.medium.com/max/795/1*nAZV-L2AKNR7B3NNvdukQA.png" /></figure><h4>1. Introduction</h4><p>While it is well known that the set of real numbers is uncountable, here I am going to:</p><ul><li>introduce difference between <strong>known</strong> real numbers and <strong>unknown</strong> ones,</li><li>illustrate why all currently known real numbers are countable,</li><li>illustrate why yet unknown real numbers will also be countable, once discovered,</li><li>question what remains beyond those real numbers, as uncountable.</li></ul><p>At the end we will see that all real numbers that we dealt with in any field of mathematics, were always countable, if looking from some new perspective.</p><p>This story is organized in the following way:</p><ul><li>In chapter 2 we will recall the 2 types of infinities — countable infinity and uncountable infinity,</li><li>In chapter 3 we will recall the famous proof from 1891 made by George Cantor, which shows why those 2 types of infinities are “not of same size”,</li><li>Next in chapter 4 we will review how real numbers are defined today, as well as will pick a subset from them, called “known real numbers”,</li><li>In chapter 5 we will make brief recall about how positional numeral systems work (decimal, binary, hexadecimal), as we will use them intensively in the next chapter,</li><li>Which is chapter 6, where the main point of this story will be presented, stating that all known real numbers are actually countable,</li><li>Next in chapter 7 we will speak about yet unknown real numbers and such numbers which will always remain unknown to us, and will raise question about “existence” of the latter ones,</li><li>And in the last chapter we will explain how those findings fit with Cantor’s mentioned proof.</li></ul><h4>2. Recalling countable vs. uncountable infinities</h4><p>Since the year 1874 mathematicians agreed that there are 2 types of infinities: a “countable infinity”, and an “uncountable infinity”. A countable infinity is the one for which we can actually “count” all its elements by natural numbers (i.e. 1, 2, 3, 4, …).</p><p>A simple example of a countable infinite set are all powers of 10:</p><blockquote>1 — 10<br>2 — 100<br>3 — 1&#39;000<br>4 — 10&#39;000<br>… and so on.</blockquote><p>Another example of a countable infinity can be set of all possible sequences of characters “a” and “b” which strictly interleave:</p><blockquote>1 — “a”<br>2 — “ab”<br>3 — “aba”<br>4 — “abab”<br>5 — “ababa”<br>… and so on.</blockquote><p>So in both cases we were able to make exact 1-to-1 correspondence between all the listed objects and natural numbers.</p><p>The other type of infinity — uncountable infinity, is the one for which natural numbers “will not be enough” to cover all its elements. So in some sense, it has “more” elements in it than there are natural numbers.</p><p>An example of uncountable infinite set are all real numbers in range [0, 1). Those include numbers:</p><blockquote>0.5 , 1/3 , 1/√‾2 , 1/√‾3 , 1/e , π-3 , 1/√‾√‾2, … and so on.</blockquote><p>Another example are all possible infinite sequences of decimal digits:</p><blockquote>121212121212…<br>775349895436…<br>797531212678…<br>… and so on.</blockquote><p>By the way, note that those 2 uncountable infinite sets actually correspond between each other, because putting “0.” before each infinite sequence of decimal digits will result in decimal representation of a real number from range [0,1).</p><blockquote><strong>0.</strong>121212121212…<br><strong>0.</strong>775349895436…<br><strong>0.</strong>797531212678…<br>… and so on.</blockquote><p>So those 2 sets really belong to same type of infinity, because we just managed to make unique 1-to-1 correspondence between all their elements.</p><p>In 1891, mathematician George Cantor has proven that we can never make 1-to-1 correspondence between all elements of an uncountable infinity and a countable infinity (i.e. all the natural numbers). The proof was later called as “Cantor’s diagonal argument”. It is in fact quite simple, and there is an excellent animation on that in [1]. That is the reason why starting from mentioned date, mathematicians use to differentiate between those 2 types of infinities.</p><h4><strong>3. Recalling Cantor’s diagonal argument</strong></h4><blockquote>&lt;you can skip this section, if you are aware of the proof why there can’t be 1-to-1 matching between countable and uncountable sets, otherwise called as Cantor’s diagonal argument&gt;</blockquote><p>In this section, I want to briefly remind about Cantor’s diagonal argument, which is a short proof of why there can’t exist 1-to-1 mapping between all elements of a countable and an uncountable infinite sets.</p><p>The proof takes all natural numbers as the countable set, and all possible infinite series of decimal digits as the uncountable set.</p><figure><img alt="Imagination of 1-to-1 mapping between all natural numbers and all infinite decimal series" src="https://cdn-images-1.medium.com/max/795/1*GLua-ufwCwUH38FApB7SRg.png" /><figcaption><em>Imagination of 1-to-1 mapping between all natural numbers (orange circle) <br>and all infinite decimal series (blue circle).</em></figcaption></figure><p>Let’s start from the opposite and assume that we somehow managed to construct the 1-to-1 mapping between all elements of the countable set (i.e. natural numbers), and all elements of the uncountable set (i.e. infinite decimal series). In that case, we should be able to write that mapping down, which, for example, might result in something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*juivf-ct9bF-hS_aBDuLWQ.png" /><figcaption><em>Top-left part of the hypothetical 1-to-1 mapping between all natural numbers <br>(left column), and all infinite decimal series (right column).</em></figcaption></figure><p>So all natural numbers are written here in increasing order. The table expands infinitely both downwards and rightwards.</p><p>Now, let’s take the sequence of digits which appeared on diagonal of the right column of the table, starting from top-left corner, and write them down separately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*iyIZmEAZSTPXlLaG0TH7qA.png" /><figcaption><em>Highlighted diagonal (red) in the hypothetical mapping between all natural numbers <br>and all possible infinite decimal series.</em></figcaption></figure><p>After which let’s change every digit of the diagonal (i.e. change the written down digits, and not content of the table). For example, let’s increment every digit by 1, and for digit ‘9’, let’s just reset it to ‘0’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*9exbgi2TacPkigtkHqRlwg.png" /><figcaption><em>Alteration of the digits from highlighted diagonal.</em></figcaption></figure><p>We will call this new series as “altered diagonal”.</p><p>Now, the altered diagonal is in its turn some other infinite decimal series, which means that it should also be present in the table. Remember, we agreed that the table has all possible infinite decimal series in it.</p><p>So assume that we found the altered diagonal alongside some natural number ‘k’, in the table (i.e. at row ‘k’). Finally, let’s view on k’th digit of that row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*ewavXug1Ie603mKzFxfq_Q.png" /><figcaption><em>Spotting the k’th digit of k’th decimal series, value of which is contradictory.</em></figcaption></figure><p>So we are speaking about the digit at row ‘k’ and column ‘k’ of right side of the table.</p><p>Now the question is: what should be value of that digit? From one side, it resides on the diagonal of the table, content of which we had initially written down. From the other side, it resides on the row ‘k’, content of which is the altered content of diagonal. So for example, if originally on the diagonal that digit had value ‘4’, then after taking the diagonal and altering it, that digit should become ‘5’. Both ‘4’ and ‘5’ can’t reside in same cell of the table, which brings us to contradiction.</p><p>This means that our assumption of finding altered diagonal on some row ‘k’ was false, as well as our initial assumption that the table will contain all possible infinite decimal series was also false. So we come to conclusion that it is impossible to construct 1-to-1 mapping between all natural numbers (i.e. countable set) and all possible infinite decimal series (i.e. uncountable set).</p><p>That is Cantor’s proof of why all elements of a countable set can’t be 1-to-1 matched with all elements of an uncountable set.</p><h4><strong>4. The problem with definition of real numbers</strong></h4><p>So as we have recalled in chapter 2, real numbers from half-open range [0,1) form an uncountable infinity (i.e. such an infinite set which can not be counted as 1, 2, 3, 4, …). Obviously, all real numbers from unbounded range (-∞, +∞) also form then an uncountable infinity.</p><p>Very well, but let’s go back a bit and start from definition of real number. Wikipedia gives us:</p><blockquote>Real numbers can be thought of as all points on a <a href="https://en.wikipedia.org/wiki/Line_(geometry)">line</a> called the <a href="https://en.wikipedia.org/wiki/Number_line">number line</a>.</blockquote><p>We see that this is not a strict mathematical definition. Actually it tries to be a visual one.</p><p>Alright, here is another definition from same wiki page:</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Mathematics">mathematics</a>, a real number is a <a href="https://en.wikipedia.org/wiki/Number">number</a> that can be used to <a href="https://en.wikipedia.org/wiki/Measurement">measure</a> a continuous one-<a href="https://en.wikipedia.org/wiki/Dimension">dimensional</a> <a href="https://en.wikipedia.org/wiki/Quantity">quantity</a> such as a <a href="https://en.wikipedia.org/wiki/Distance">distance</a>, <a href="https://en.wikipedia.org/wiki/Time">duration</a> or <a href="https://en.wikipedia.org/wiki/Temperature">temperature</a>. Here, <em>continuous</em> means that pairs of values can have arbitrarily small differences. Every real number can be almost uniquely represented by an infinite <a href="https://en.wikipedia.org/wiki/Decimal_expansion">decimal expansion</a>.</blockquote><p>Well, we know that rational numbers (i.e. fractions of form “<em>a</em>/<em>b</em>” where both <em>a</em> and <em>b</em> are integers) are also capable of representing arbitrarily small differences. So we should focus instead on the last part of that definition which states about “infinite decimal expansion”, which is same as “infinite decimal series” or “infinite sequence of decimal digits”. Cantor’s proof of uncountability of real numbers is also based on this definition, i.e. it views real numbers as infinite decimal series.</p><p>By the way, same is stated in definition taken from Britannica:</p><blockquote>Real number, in <a href="https://www.britannica.com/science/mathematics">mathematics</a>, a quantity that can be expressed as an <a href="https://www.merriam-webster.com/dictionary/infinite">infinite</a> <a href="https://www.britannica.com/science/decimal">decimal</a> expansion.</blockquote><p>And here is first point where I want to grab your attention on. There are some infinite decimal expansions, which can be exactly specified by us, and there are others which are currently out of our capability of specifying them.</p><ul><li>Obviously, numbers like “4.55” or “9.125” can be precisely defined just using finite amount of digits.</li><li>Next, rational numbers like “20.33333…” (also denoted as “20.(3)”) or “12.35353535…” (denoted as “12.(35)”) can also be precisely pointed to by using finite amount of digits and symbols. For example “20.(3)” is same as “61/3” and “12.(35)” is same as “1223/99”.</li><li>Next, addressing irrational number like √‾2 or √‾3 still can be done using finite amount of words or symbols. Using words, number √‾2 can be pointed to as “the number which multiplied by itself gives 2”. And using symbols we can just write it as “√‾2”. There is no ambiguity in both forms, and we know exactly what real number we are pointing to.</li><li>Moving forward, and taking numbers like <em>π</em> and <em>e</em>, we can still precisely point them out in finite sequence of symbols, as “<em>π </em>= 4*∑((-1^<em>n</em>)/(2<em>n</em>+1))” (with <em>n</em> ranging in [0,+∞)), and “<em>e = </em>∑(1/<em>n</em>!)” (again with <em>n</em> ranging in [0,+∞)), or in finite sequence of words, like - “infinite sum of fractions of 1 over <em>n</em> factorial”.</li></ul><p>Of course, combining together all known symbols and words which are used to describe numbers, again will give us such numbers which we are able to precisely specify with finite amount of words (or symbols). Examples are: √‾2<em>π, e³, sin</em>(<em>π</em>/17)+4<em>.</em></p><p>So concluding this chapter, we have observed here that any real number which is known to us (i.e. value of which can be specified precisely), that real number can be described in finite amount of English words or mathematical symbols.</p><h4><strong>5. A brief recall of positional numeral systems</strong></h4><blockquote>&lt;you can skip this chapter, if you are familiar how positional numeral systems work&gt;</blockquote><p>We are all used to read and write numbers with 10 digits — from ‘0’ to ‘9’. However, that is not the only possible method for representing numbers. In this chapter I want to make a brief recall on how else numbers can be represented, as later we are going to introduce some other method for mapping all known real values to natural numbers.</p><p>The method by which we use to read and write numbers is called “decimal positional numeral system”.</p><ul><li>Why is it “positional”? Because position at which a digit is written affects overall value. For example in number “125” digit “5” is written at the end, which means that it adds only 5 to the result. While in “512” the same digit “5” is written at first place, which means that it adds value of 500 to the result.</li><li>Why is it “decimal”? Because it uses 10 digits — from ‘0’ to ‘9’. By the way, number of digits being used is also called the “base” of positional system. So we are used to positional numeral system with <em>base</em>=10.</li></ul><p>Now, how is the value of any written number being calculated? Each digit has its weight, which is increasing if reading digits from right to left. Weight of last digit is always equal to 1, weight of second-last digit is 10, weight of the third-last digit is 100, and so on.</p><figure><img alt="Values of weights of digits of number 5&#39;137, written in decimal positional system." src="https://cdn-images-1.medium.com/max/1008/1*nGNTHzRNGPkvLGfHK6A4Lg.png" /><figcaption><em>Weights of digits, in decimal positional system.</em></figcaption></figure><p>So weights are being multiplied by 10 when moving from right to left. And the value is obtained by summing up all digits, multiplied by their corresponding weights.</p><figure><img alt="Illustration of how value 5&#39;137 is obtained, when summing up its digits multiplied by their weights." src="https://cdn-images-1.medium.com/max/795/1*ek3aCvTVbs2HuNABa6cyOQ.png" /><figcaption><em>How a value is obtained, within decimal positional notation.</em></figcaption></figure><p>That is how our decimal positional numeral system works. But there do exist other numeral systems too. For example, the one used in computers is binary positional numeral system, which roughly speaking, differs from our decimal system only by having 2 digits, instead of 10. So it has only digits ‘0’ and ‘1’ (i.e. its <em>base</em>=2), and weights of digits are multiplied here by 2 (instead of 10), when moving from right to left.</p><figure><img alt="Illustration of how value 53 is constructed within binary positional system." src="https://cdn-images-1.medium.com/max/795/1*L9LVpUyjT0-_hWR511Ic3A.png" /><figcaption><em>How a value is obtained, within binary positional notation.</em></figcaption></figure><p>So the number written there as “110101” is actually equal to 53.</p><p>Other positional systems also exist with base greater than 10. For example, hexadecimal positional system uses 16 digits (digits from ‘0’ to ‘9’, then 6 letters ‘A’, ‘B’, …, ‘F’, which correspond to values 10, 11, … 15). Calculations are performed with same formulas, but with <em>base</em>=16:</p><figure><img alt="Illustration of how value 23&#39;267 is constructed within hexadecimal positional system." src="https://cdn-images-1.medium.com/max/795/1*2HOfK3MZ90cJKZzh6RafrA.png" /><figcaption><em>How a value is obtained, within hexadecimal positional notation.</em></figcaption></figure><p>So what’s common in all positional numeral systems is:</p><ul><li>count of different digits is equal to “base” of that system,</li><li>each digit has its weight,</li><li>weight of last digit is always 1,</li><li>weight of every previous digit is “base” times larger than weight of the next digit.</li></ul><p>With positional numeral systems every number is represented in a unique way, and every representations uniquely maps to a number.</p><h4><strong>6. Why all descriptions are countable</strong></h4><p>The next thing that I want to grab your attention to — why am I so concentrated on the numbers which can be pointed out using “finite amount of words or mathematical symbols”? Because as I will show in this chapter, all such numbers are countable.</p><p>See, let’s take an English sentence which denotes some real number:</p><blockquote>“The number which multiplied by itself gives one half.”</blockquote><p>So here we are talking about √‾1/2 = 0.70710 67811… .</p><p>We know that there is finite amount of English words. For simplicity let’s assume that if prefix or suffix of a word is different, then those are just different words, so for example “multiple”, “multiply”, “multiples” are 3 different words for us. Now, Google says that currently there are around 170&#39;000 English words in use. Considering that different prefixes and suffixes mean for us different words, let’s take number of words equal to 1&#39;000&#39;000 = 10⁶ then.</p><p>Next, let’s write all that 10⁶ words down in alphabetical order, as well as number them with incremental integers:</p><figure><img alt="Example of ordering of all English words by incrementing natural numbers (keys)." src="https://cdn-images-1.medium.com/max/291/1*T2KG2NIf19m5Rq-6ZxOacQ.png" /><figcaption><em>Ordering all English words by incrementing natural numbers (keys).</em></figcaption></figure><p>We will call that integers as “keys” here. So now we have all possible words numerated. And it actually means that we can also unambiguously map any English sentence to natural number too. Let’s take the sentence mentioned above and beneath every its word write the corresponding key:</p><figure><img alt="Example of replacing of all words in an English sentence by corresponding keys." src="https://cdn-images-1.medium.com/max/795/1*9ug7jNdhJMB4M5_VRQOTfg.png" /><figcaption><em>Replacing all words in an English sentence by corresponding keys.</em></figcaption></figure><p>After which we can look on that sequence of keys as on a much larger value, written in another positional numeral system with <em>base</em>=1&#39;000&#39;000 (instead of our familiar decimal positional system). So every word (or its key) will be kind of “digit” in that new positional system. Count of all possible words (keys) will form its base, which is equal to one million (10⁶) here. After those assumptions, the value of that sentence can be calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*V-9NCf3BYMFZbIK8kf0s3Q.png" /><figcaption><em>Calculating the number which corresponds to entire English sentence,<br>using positional numeral system with base=1&#39;000&#39;000.</em></figcaption></figure><p>which is of course quite a big natural number, but still finite, and uniquely identifying the original sentence. So once again, keys of words play role of “digits” in this new positional numeral system, and weights of that “digits” here are powers of one million (10⁶), and weight of any “digit” is one million times larger than the weight of its next “digit”.</p><p>Same operations can be performed to any other English sentence, which identifies some real number. This means that upon having a real number in our mind, we can unambiguously map it to some natural number.</p><p>We know very well that it is possible to describe real numbers not only by English words but also with help of mathematical symbols. For example the same square root of one half is composed from 4 symbols:</p><blockquote>√‾1/2</blockquote><p>And base of natural logarithm <em>e</em> is described as:</p><blockquote>∑ {n ∈ [0, ∞)} 1/(n!)</blockquote><p>… which gives 16 symbols. So same principle of mapping real values to natural numbers can be applied within this notation too. We can number down all possible mathematical symbols, including decimal digits, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*V8-1u2QuWducps1wqZcfug.png" /><figcaption><em>Ordering all symbols, which might be encountered in mathematical formulas<br>by incrementing natural numbers (keys).</em></figcaption></figure><p>Then, when writing a formula in a line, we can write key of every symbol beneath it, like this:</p><figure><img alt="Replacing symbols of formula for “square root of one half” by corresponding keys." src="https://cdn-images-1.medium.com/max/622/1*H0_1Cbg3gVPGU5Jurjd53A.png" /><figcaption><em>Replacing all symbols of a formula by corresponding keys.</em></figcaption></figure><p>Let’s say we will have no more than 100 symbols in use. The sequence of keys, where each is in range [0, 99], will form another larger natural number if we will look at it as a sequence of “digits” in another positional numeral system with <em>base</em>=100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*G_X6O3qAfUl7eFjdVqiSAQ.png" /><figcaption><em>Calculating the number which corresponds to entire formula,<br>using positional numeral system with base=100.</em></figcaption></figure><p>Finally, we obtained that natural number 41&#39;011&#39;302 corresponds to √‾1/2.</p><p>So here again, having any possible mathematical notation of a real number, we managed to construct a mapping from it to some large natural number. And this mapping is unambiguous, since we can:</p><ul><li>do reverse calculation,</li><li>obtain sequence of keys,</li><li>obtain sequence of symbols corresponding to that keys,</li><li>calculate the real number, which is stated by the obtained formula.</li></ul><p>Of course, not every such large natural number will correspond to some real number. That is because if we randomly take a large natural number, it will represent some random sequence of English words (or mathematical symbols), so the probability that such random sequence will be meaningful, and will identify some real number is quite low. So only some small subset of those large natural numbers will correspond to real numbers. But that fact doesn’t affect our judgements about countability here, as it is known that every subset of a countable set is also countable. So, given that all natural numbers are countable, their subset corresponding in the mentioned ways to known real numbers, will also be countable.</p><p>From the other side, both in English words case and mathematical symbols case, the mappings are not unique, as same real number can often be described with a bit different sentences as well as a bit different formulas. But that fact also doesn’t affect our judgements within scope of this paper.</p><figure><img alt="Several examples of how different formulas describe same real number." src="https://cdn-images-1.medium.com/max/795/1*mw9v6x8EdING_QZQg7G_ZA.png" /><figcaption><em>Examples of how different formulas describe same real number.</em></figcaption></figure><p>The reason is simple. Here we are interested in “covering” all known real numbers by natural indexes (1, 2, 3, …). Now, if several indexes cover same real number, that is OK for us, as long as every other known real number remains “covered” by at least 1 natural index. And it actually remains, because every real number that we know can be still described at least by one English sentence (or by one mathematical formula).</p><p>Concluding this chapter, its purpose was to illustrate that any real number which can be described in finite amount of English words or mathematical symbols, can be unambiguously mapped to a specific natural number. Obviously, any real number that we know can be described by finite words and symbols. So all known real numbers can be mapped onto natural numbers.</p><p>This means that all known real numbers are countable.</p><h4><strong>7. What about yet unknown real numbers?</strong></h4><p>Our currently known set of real numbers was not the same in the past. Some real numbers were discovered sooner, some others later. For example, square root of 2 (√‾2 = 1.41421 35623 …) was originally mentioned around the end of twelfth century in the works of the Moroccan mathematician Ibn al-Yasamin, the base of natural logarithm (<em>e</em> = 2.71828 18284 …) was first mentioned by Jacob Bernoulli in 1683, and Euler’s constant (<em>γ</em> = 0.57721 56649 …) originally appeared in 1734 in a paper by the Swiss mathematician Leonhard Euler.</p><p>It is quite reasonable to assume that new real numbers will continue to be discovered in future.</p><figure><img alt="Illustration of nesting of currently known real numbers into yet unknown real numbers." src="https://cdn-images-1.medium.com/max/646/1*SJ31ZC89_0fROS6_rGPNRw.png" /><figcaption><em>Differentiation between currently known and yet unknown real numbers.</em></figcaption></figure><p>However, the key idea remains: regardless of when we will discover new real numbers, we will still be able to express them in finite amount of words (or finite amount of symbols, even if there will be need to introduce new symbols). Which means that they all, together with currently known real numbers, will continue to remain countable.</p><p>Very well, if all the real numbers that we can point to (now and in the future) are countable, then what does remain as uncountable?</p><figure><img alt="Nesting of set of currently known real numbers into set of yet unknown real numbers, which themselves are nested into set of all real numbers." src="https://cdn-images-1.medium.com/max/727/1*nY6t4r_qN3K_fHS56xWvAw.png" /><figcaption><em>Differentiation between currently known, yet unknown, <br>and generally all real numbers.</em></figcaption></figure><p>Those are the numbers which we will be never able to point to, if using finite sequence of words and symbols. So generally, those are the numbers which we will never be able to realize with our mental and perceptional capabilities. And this leads us to a philosophical question:</p><blockquote>If there are numbers that we will never be able to point to, and neither be able to realize with our mental and perceptional capabilities, then do such numbers actually exist?</blockquote><p>So we neither know their exact values, nor how we can approximate them, nor if they have any physical meaning or not… Aren’t we then just misleading ourselves by using unclear definitions for real numbers like “any infinite sequence of decimal digits” or like “all the points on number plane”?</p><p>And this is a question which I would like to leave open within the scope of this story.</p><h4><strong>8. How this all fits together with Cantor’s diagonal argument</strong></h4><p>We have observed that all real numbers (and particularly, all the real numbers from half-opened range [0,1) ) , that we are capable to point to, are countable. But how does that fit with famous Cantor’s diagonal argument (recalled by us in chapter 3), upon which all reals from range [0,1) are uncountable? Well, the explanation is simple: majority of those real numbers from half-opened range [0,1) are beyond our capability of exactly specifying them.</p><p>Saying the phrase “we can describe a number with finite amount of words or symbols” is also same as saying “we have a method of obtaining any <em>k</em>-th digit (<em>k</em> ∈ <em>[1, +∞)</em>) of its infinite decimal expansion”. This holds true for example for all the 4 categories of real numbers that we have listed in chapter 4. Yes, in general the greater the ‘<em>k</em>’, the more operations will be needed to perform in order to obtain value of that <em>k</em>-th digit, but still we can always do it in finite amount of time.</p><p>Meanwhile that is not true for the real numbers which are written top-down in the table within Cantor’s proof (chapter 3), because there it is just said that “some infinite sequences of decimal digits” are written down, while neither are those digits specified, nor a method is given for obtaining those digits. In other words, in Cantor’s proof we are not listing out real numbers, because we are not listing out numbers in general. We just list out something which looks similar to them. Those are not numbers, because for majority of them, we don’t even know their exact value… do we?</p><p>And that is the reason why those incompletely-defined infinite decimal expansions in Cantor’s diagonal argument really fall out of the scope of a countable infinity.</p><h4><strong>9. Conclusion</strong></h4><p>In the current story we have:</p><ol><li>differentiated between all the real numbers which are known to us, and the ones which are unknown,</li><li>explained why all the known real numbers are countable,</li><li>explained why the real numbers which will be invented in future will still remain countable,</li><li>and halted upon question, asking if all the other real numbers which form uncountable infinity, actually exist.</li></ol><p>It will be very interesting for me to read your thoughts and feedback on all statements made here. So please don’t hesitate to write [long] comments below :-)</p><p>And thank you so much for reading till the end!</p><blockquote>Thanks to Arman Darbinyan, Hayk Aslanyan, Vachagan Margaryan and Hayk Ghazaryan for helping in validation of the idea.</blockquote><blockquote>Huge thanks to David Ayrapetyan for reviewing the draft 2 times, and making a lot of contextual and grammatical corrections.</blockquote><blockquote>Illustrations made by Asya Papyan: <a href="https://www.behance.net/asyapapyan">https://www.behance.net/asyapapyan</a></blockquote><h4><strong>References</strong></h4><p>[1] — “Math’s Fundamental Flaw” (by Veritasium) : <a href="https://youtu.be/HeQX2HjkcNo">https://youtu.be/HeQX2HjkcNo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f09e57f83f4d" width="1" height="1" alt=""><hr><p><a href="https://www.cantorsparadise.com/why-all-known-real-numbers-are-actually-countable-f09e57f83f4d">Why all known real numbers are actually countable</a> was originally published in <a href="https://www.cantorsparadise.com/">Cantor’s Paradise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>