Number systems and bases
A number is a quantity; the base decides how it is written. In base 10 each position is worth a power of 10; in base 2 (binary)…
Behind every number there is a representation. In this lesson you will work with numeral bases, bitwise operators, masks and flags, modular arithmetic (powers and inverses) and the exact Decimal and Fraction types. You will see how to solve with a single operation problems that otherwise need loops, and why binary decimals are not exact.
A number is a quantity; the base decides how it is written. In base 10 each position is worth a power of 10; in base 2 (binary)…
Bitwise operators work on each bit of the integers separately. They are very fast and let you solve some problems with an…
An integer can store many yes/no flags at once: bit i tells whether flag i is on. It is the usual way to represent permissions…
Modular arithmetic works with remainders: “what time will it be in 100 hours” is (hour + 100) % 24 . It is the basis of check…
float stores numbers in binary, and that is why 0.1 cannot be represented exactly. For money, accounting or calculations that…
The same number can be written in any base. To convert it from decimal to base b , divide by the base and keep the remainders…
Computers store negative integers in two's complement : with n bits, the value -x is stored as 2**n - x . The result is the same…
The popcount of a number is the amount of 1 bits in its binary form. The trick n & (n - 1) always clears the lowest set bit, so…
A power of two has a single 1 bit. That is why n & (n - 1) is 0 only for them, and the check needs no loops or logarithms.
The XOR operator satisfies a ^ a == 0 and a ^ 0 == a . If you XOR all the numbers, those that appear twice cancel out and the one…
An integer can act as a set of flags: bit i is 1 if flag i is on. With |= , &= ~ and ^= you change a flag, and with (m >> i) & 1…
The Gray code orders the n -bit numbers so that two consecutive ones differ in a single bit. Value i of the sequence is obtained…
Computing base**exp % mod with huge numbers is infeasible if you multiply exp times. Fast exponentiation walks the bits of the…
The modular inverse of a modulo m is the number x between 0 and m-1 such that a * x % m == 1 . It exists only if a and m are…
With Fraction from the fractions module, operations with fractions are exact, without the rounding errors of float . The result…