{"id":142,"date":"2026-11-13T12:32:35","date_gmt":"2026-11-13T04:32:35","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-binary-exponentiation-squares-a-power\/"},"modified":"2026-11-13T21:51:11","modified_gmt":"2026-11-13T13:51:11","slug":"how-binary-exponentiation-squares-a-power","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-binary-exponentiation-squares-a-power\/","title":{"rendered":"How binary exponentiation squares a power"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Binary exponentiation<\/strong> computes a^e with <strong>O(log e)<\/strong> multiplications by scanning the bits of the exponent. The square-and-multiply loop squares a running power for every bit and multiplies by the base when the bit is 1. The same loop with every multiplication reduced modulo m computes a^e mod m. It is the multiplication engine inside RSA, Diffie-Hellman, Miller-Rabin, and any other algorithm that needs a large power.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Multiplying by a, e times, performs e\u22121 multiplications. The binary expansion of e writes the power as a product of terms a^{2^k} for the bits that are set. Those terms are successive squares. The algorithm never builds a multiplication chain fancier than this one. Addition chains can be shorter for a fixed exponent and are not what this loop does.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Modular reduction after every multiply keeps the operands the size of m. Reducing only at the end creates an enormous integer and is still mathematically right and practically wrong.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The loop returns a^e, or a^e mod m if every product is reduced. The number of squarings is the bit length of e, and the number of extra multiplies is the number of 1 bits. Time is O(log e) multiplications. Extra memory is a few integers. A negative exponent is not handled unless a is inverted modulo m first, which needs the extended Euclidean algorithm and a coprime a.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Left-to-right and right-to-left scans both work and associate the multiplications differently. They return the same value. An off-by-one in the initial power, starting from 0 instead of 1, returns 0 for every positive exponent.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Set the result to 1 and the base to a modulo m if a modulus is in use. If e is 0, return 1, including the convention 0^0 if the caller has one.<\/li>\n<li>While e is positive, if the low bit of e is 1, multiply the result by the current base and reduce.<\/li>\n<li>Square the base and reduce. Shift e right by one bit.<\/li>\n<li>The right-to-left loop just described reads bits from low to high. The left-to-right loop scans from the high bit, squaring the result each time and multiplying by a when the bit is 1.<\/li>\n<li>For a negative exponent modulo m, replace a by its inverse and negate the exponent before entering the loop. If the inverse does not exist, the power is undefined in the residues.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The logarithmic bound counts multiplications, not bit operations. Fast multiplication changes the cost of each multiply and does not change the number of them. The loop is not a general addition-chain optimizer. Modular exponentiation with a secret exponent should use a constant-time ladder in cryptographic code. This description is the arithmetic algorithm, not a side-channel-resistant implementation.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the result starts at zero<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Initialize the result to 0<\/td>\n<td>Every multiply stays 0. The empty product, a^0 and the starting value of a positive power, is 1.<\/td>\n<\/tr>\n<tr>\n<td>Reduce modulo m only after the full power is known<\/td>\n<td>The integer a^e has e\u00b7log a bits. The modular loop keeps every intermediate below m.<\/td>\n<\/tr>\n<tr>\n<td>Shift the exponent and forget to square the base<\/td>\n<td>The bit positions then all multiply the original base. The result is a multiplied by itself once per set bit, not a^e.<\/td>\n<\/tr>\n<tr>\n<td>Use the fast loop for a secret exponent with a data-dependent branch on the bit<\/td>\n<td>The arithmetic result is right and the timing leaks the bits. Cryptographic code needs a fixed sequence of multiplies.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">The modular inverse that a negative exponent needs is the extended Euclidean algorithm. Miller-Rabin, RSA, and Diffie-Hellman all call this loop. Binary exponentiation is the square-and-multiply power.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The Bash script and the Python script square the base for each bit of the exponent and reduce modulo 1000 at every multiplication. Both print <code>24<\/code>, which is 2^10 mod 1000.<\/p>\n\n<pre><code class=\"language-bash\">base=2\nexp=10\nmod=1000\nresult=1\nbase=$((base % mod))\nwhile (( exp &gt; 0 )); do\n  if (( exp &amp; 1 )); then result=$(( (result * base) % mod )); fi\n  base=$(( (base * base) % mod ))\n  exp=$((exp &gt;&gt; 1))\ndone\necho &quot;$result&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def modpow(base, exp, mod):\n    result = 1\n    base %= mod\n    while exp:\n        if exp &amp; 1:\n            result = result * base % mod\n        base = base * base % mod\n        exp &gt;&gt;= 1\n    return result\n\nassert modpow(2, 10, 1000) == 24\nprint(modpow(2, 10, 1000))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Binary exponentiation is the modular power inside <strong>RSA**, <\/strong>Diffie-Hellman**, and every <code>pow(base, exp, mod)<\/code> in a crypto library. OpenSSL and the Python built-in both square-and-multiply. Multiplying in a loop is the same function and far too slow for a 2048-bit exponent.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop the O(e) multiply loop for any exponent longer than a few bits. Use square-and-multiply. Keep a constant-time variant when the exponent is a secret. The mathematical loop is the one described here.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for binary exponentiation returns the square-and-multiply bit scan and the initial value 1. <strong>Binary exponentiation computes a to the e with O(log e) multiplications by squaring for every bit and multiplying when the bit is set.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Binary exponentiation computes a^e with O(log e) multiplications by scanning the bits of the exponent. The square-and-multiply loop squares a running power for every bit and multiplies by the base when the bit is 1. The same loop with every multiplication reduced modulo m computes a^e mod&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,42],"tags":[],"class_list":["post-142","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-number-theory"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/142","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=142"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/142\/revisions"}],"predecessor-version":[{"id":541,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/142\/revisions\/541"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=142"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=142"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}