The algorithm attempts to compute the cubic root of integer n
using bisection. The context is the final step of Håstad's broadcast attack, in which n
can be thousands of bits, and is expected to be exactly the cube of an integer if all went well beforehand.
Why does bit length work here?
The expression
hi = 1 << ((n.bit_length() + 2) // 3)
yields a rough approximation of the desired result, by taking the logarithm to base 2, dividing by 3 (with some offset), and exponentiating to base 2. Let's prove the result is always by excess:
- For integer
n >= 0
, by specification of int.bit_length(), n.bit_length()
is the smallest non-negative integer x
such that n < 2**x
.
- For every non-negative integer
x
, if holds x <= ((x + 2) // 3) * 3
- The function which for input
x
yields 2**x
(that is two to the x
th power) is nondecreasing
- Therefore
n < 2**(((x + 2) // 3) * 3)
- By a standard property of powers,
2**(((x + 2) // 3) * 3)
is (2**((x + 2) // 3))**3
- For every non-negative integer
i
, it holds (1 << i) == (2**i)
- Therefore the initial value of
hi
is such that n < hi**3
and hi >= 0
.
The loop invariant condition of the bisection algorithm
lo <= hi and (lo-1)**3 < n and n <= hi**3
is now easily established by induction: it hold before the while loop, and is maintained by the changes made in the loop (the proof uses that the function which for input x
yields x**3
is nondecreasing), hence is valid on exit. Bisection narrows the gap between lo
and hi
by a factor about 2 at each loop, and terminates with lo >= hi
. It follows that on output the function returns the smallest integer lo
such that lo**3 >= n
, which is the integer cubic root of n
by excess.
high
atnum // 2
ornum // 3
" is not intelligible, first becausehigh
andnum
are not part of the code, second because initializing withhi = n // 2
orhi = n // 3
results in code that's functional whenevern > 5
.