Bit operations, greatest common divisors, primes and modular arithmetic for coding problems.
You work on a chat app. Your team lead lists three jobs:
All three jobs treat a number as a row of switches, or as a quantity you keep small by taking remainders. This lesson covers both. It also says which language does what, because bit tricks are where Python, Java, C++ and JavaScript behave differently.
You write numbers in decimal: each place is worth ten times the place to its right. In binary each place is worth two times the place to its right, and each place holds only 0 or 1. A binary digit is a bit.
| Place value | 8 | 4 | 2 | 1 |
|---|---|---|---|---|
| Bits of 13 | 1 | 1 | 0 | 1 |
So 1101 is 8 + 4 + 0 + 1 = 13. Counting up: 0, 1, 10, 11, 100, 101, and so on. Each extra bit doubles the number of patterns.
8 bits (a byte) give 2^8 = 256 patterns, 0 to 255. 16 bits give 65,536, and 32 bits give 4,294,967,296.
Programmers often write bits in groups of four, as a hexadecimal digit. Hexadecimal is only a shorthand: 1101 is d.
A computer has no minus sign for a row of bits. A signed integer of w bits reads the top bit as worth -2^(w-1) instead of +2^(w-1). This is two's complement. To negate a number, flip every bit and add 1.
| 8-bit pattern | Unsigned value | Signed value |
|---|---|---|
00000101 |
5 | 5 |
11111010 (all bits of 5 flipped) |
250 | -6 |
11111011 (flipped, plus 1) |
251 | -5 |
11111111 |
255 | -1 |
10000000 |
128 | -128 |
Negative numbers use two's complement: flip every bit of 5 and add 1 to get minus 5. In eight bits the top bit is worth minus 128.
An 8-bit signed value runs from -128 to 127, so there is one more negative than positive number. A 32-bit int runs from -2,147,483,648 to 2,147,483,647, and a 64-bit long up to 9,223,372,036,854,775,807. Flipping all bits of x gives -x - 1, so ~5 is -6 in every language here.
Each language shows a negative number's bits differently.
| Language | Bits of -5 |
|---|---|
| Python | bin(-5) is '-0b101': a sign and the bits of 5. Ints behave as if infinitely many 1 bits sit on the left, so -5 & 0xFF is 251 |
| Java | Integer.toBinaryString(-5) gives the 32 bits 11111111111111111111111111111011 |
| JavaScript | (-5 >>> 0).toString(2) gives the same 32 bits. (-5).toString(2) is '-101' |
| C++ | std::bitset<32>(-5) prints the 32 bits |
Predict what happens
Q In an 8-bit signed number, what is 10000000?
Answer: C
The top bit is worth -128 in an 8-bit signed number, and every other bit is 0. So the pattern is -128, the smallest value. Read as unsigned, the same pattern is 128.
Each of the three methods in the next beat has an everyday picture.
A hallway has two panels of 8 light switches, one for each of two people. You compare the panels switch by switch, in the same column. You can ask: which lights are on in both panels, in either panel, or in exactly one panel?
Those three questions are AND, OR and XOR. Each column is judged alone. A column never looks at its neighbours.
Two panels of light switches are compared one column at a time. AND asks which are on in both, OR in either, and XOR in exactly one.
An odometer shows 4000 and you take away 1. It shows 3999: the lowest non-zero digit dropped by one, and every 0 on its right became 9. Everything to the left did not change.
Binary works the same way. Subtracting 1 turns the lowest 1 bit into 0 and every 0 on its right into 1, and the bits to the left stay. So x and x - 1 differ in the lowest 1 bit and everything below it, and the AND of the two keeps only the part that did not change. That is x & (x - 1): the lowest 1 bit is gone.
Subtracting 1 changes the lowest 1 bit and the zeros below it, like an odometer going from 4000 to 3999. ANDing with x clears that bit.
A party list has one tick box for each of 8 friends. Ticking a box adds a friend, unticking removes one, and two lists can be merged by ticking every box that either list ticked.
A bitmask is that list stored as one number. Bit i is the box for item i, so a small set fits in one integer, and set operations become single operations on bits.
Take x = 12 and y = 10. In 8 bits, x is 00001100 and y is 00001010.
| Operator | Name | Result in 8 bits | Value |
|---|---|---|---|
x & y |
AND: 1 where both are 1 | 00001000 |
8 |
x | y |
OR: 1 where either is 1 | 00001110 |
14 |
x ^ y |
XOR: 1 where the bits differ | 00000110 |
6 |
~x |
NOT: flip every bit | 11110011 |
-13 as signed, 243 as unsigned |
x << 1 |
Shift left: bits move left, 0 comes in | 00011000 |
24 |
x >> 2 |
Shift right: bits move right | 00000011 |
3 |
With 12 and 10 in eight bits, AND keeps the columns where both are 1, OR where either is, and XOR where they differ.
Step by step: AND of 12 and 10, one column at a time. The animated player loads in your browser.
Step by step: XOR of 12 and 10, one column at a time. The animated player loads in your browser.
A left shift by k multiplies by 2^k, until bits fall off the left end. A right shift by k divides by 2^k and rounds down, towards minus infinity. So -5 >> 1 is -3, while -5 / 2 is -2 in Java and C++, which round towards zero. Python's -5 // 2 is -3, like the shift.
JavaScript's / does not round at all: -5 / 2 is -2.5, and Math.trunc(-5 / 2) is -2.
A right shift of a negative number copies the sign bit into the new left bits, so the number stays negative. This is an arithmetic shift. Java and JavaScript also have >>>, a logical shift that always brings in 0 bits and ignores the sign.
| Language | -5 >> 1 |
-5 >>> 1 |
|---|---|---|
| Python | -3 | No such operator. Use (x & 0xFFFFFFFF) >> 1, which gives 2147483645 |
Java (int) |
-3 | 2147483645 (for a long, -5L >>> 1 is 9223372036854775805) |
| JavaScript | -3 | 2147483645 |
| C++ | -3 in every mainstream compiler, and defined as arithmetic from C++20 | No such operator. Cast to an unsigned type first: (unsigned)x >> 1 |
>>> exists so that you can treat 32 bits as an unsigned pattern, for example when you read the bits of a hash. In JavaScript, x >>> 0 also turns a negative number into its unsigned 32-bit value, so -5 >>> 0 is 4294967291.
| Language | 1 << 32 on a 32-bit int |
|---|---|
| Python | 4294967296, because ints have no limit |
| Java | 1. An int shift count uses only its low 5 bits, so 32 acts as 0. Use 1L << 32 for 4294967296 |
| JavaScript | 1, for the same reason: the count is taken mod 32 |
| C++ | Undefined behaviour. A shift by the width or more is not allowed. Use 1LL << 32 |
Shifting a 1 into the sign bit also differs. 1 << 31 is -2147483648 in Java and JavaScript. In C++, shifting a 1 into the sign bit of a signed int was undefined in C++11 and earlier, and it still is in C. Only C++20 defines it as -2147483648, so write 1u << 31 or 1LL << 31.
Each trick is one line. Here i counts from 0 at the right.
| Job | Expression | Example: x = 44 (00101100) |
|---|---|---|
| Test bit i | (x >> i) & 1 |
bit 3: 1 |
| Set bit i | x | (1 << i) |
set bit 0: 45 |
| Clear bit i | x & ~(1 << i) |
clear bit 2: 40 |
| Toggle bit i | x ^ (1 << i) |
toggle bit 5: 12 |
| Keep only the lowest 1 bit | x & -x |
4 |
| Clear the lowest 1 bit | x & (x - 1) |
40 |
x & -x works because -x is the bits of x flipped, plus 1. The plus 1 carries up to the lowest 1 bit, so below that bit and at it the two numbers agree, and above it they are opposite.
Take x = 44, which is 00101100. Then x - 1 = 43, which is 00101011. The lowest 1 bit of x (the 4) became 0, and the two 0 bits below it became 1. The AND is 00101000, which is 40.
Step by step: Clearing the lowest bit of 44, again and again. The animated player loads in your browser.
Exercise · Predict the output: Three tricks on one number. The number 108 is 1101100 in binary. What does this print: the lowest 1 bit, 108 with its lowest 1 bit cleared, and bit 3?
x = 108
print(x & -x, x & (x - 1), (x >> 3) & 1)Repeat x = x & (x - 1) until x is 0, and count the steps. For 44, the values are 44, 40, 32, 0. That is 3 steps, and 44 has three 1 bits (32, 8 and 4). The loop runs once for each 1 bit, not once for each of the 32 bits.
Languages have a built-in count:
x.bit_count() from version 3.10, or bin(x).count("1") for x of 0 or more.Integer.bitCount(x) and Long.bitCount(x).__builtin_popcount in GCC and Clang, std::popcount from C++20 (it takes only unsigned types, so write std::popcount((unsigned) x); an int does not compile), or std::bitset<32>(x).count().Negative numbers need care. Integer.bitCount(-5) and __builtin_popcount(-5) are 31, because they count the 32-bit pattern. In Python, bin(-5).count("1") is 2, because it counts the bits of 5. In Python, mask first: bin(-5 & 0xFFFFFFFF).count("1") is 31.
A power of two has exactly one 1 bit. Clearing it leaves 0. So a whole number x is a power of two when x > 0 && (x & (x - 1)) == 0.
Exercise · Break it: Find the input this power-of-two test accepts. This function says whether x is a power of two by clearing its lowest 1 bit and checking for 0. Find an input where it gives the wrong answer.
def is_power_of_two(x):
return (x & (x - 1)) == 0The test x > 0 is not optional. For x = 0, the AND is 0 too, so 0 would pass.
In Java, Integer.MIN_VALUE is 10000000...0. Subtracting 1 wraps to 01111111...1, the AND is 0, and the test says "power of two" for a negative number. In C++ the subtraction is signed overflow, which is undefined. Python gives -4294967296 for the same AND, so the test says false there, but the x > 0 check is still the habit to keep.
XOR has three useful rules: a ^ a is 0, a ^ 0 is a, and the order does not matter. So XOR of a whole list cancels every value that appears twice, and leaves the one that appears once.
| Step | Value read | Running XOR |
|---|---|---|
| Start | 0 | |
| 1 | 4 | 4 |
| 2 | 9 | 13 |
| 3 | 4 | 9 |
| 4 | 7 | 14 |
| 5 | 9 | 7 |
The ids [4, 9, 4, 7, 9] leave 7. This takes one pass and one number of memory. A hash map of counts also works, but it needs memory in proportion to the number of different ids.
Predict what happens
Q What is 6 ^ 6 ^ 3 ^ 5 ^ 5?
Answer: C
6 ^ 6 is 0, and 5 ^ 5 is 0. That leaves 0 ^ 3, which is 3. XOR cancels pairs, and it does not matter where in the list the pairs are.
Give each item a bit. A chat app has these permissions, with bit 0 on the right:
| Bit | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Permission | view | post | react | pin | invite | remove | mute | admin |
| Value | 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 |
A member who can view and post has mask 00000011, which is 3. Now the set operations are one operator each.
| Set operation | Bit operation | Example |
|---|---|---|
| Add item i | m | (1 << i) |
grant pin to 3: 3 | 8 is 11 |
| Remove item i | m & ~(1 << i) |
revoke post from 11: 11 & ~2 is 9 |
| Toggle item i | m ^ (1 << i) |
toggle react on 9: 9 ^ 4 is 13 |
| Has item i? | (m & (1 << i)) != 0 |
does 13 have pin? 13 & 8 is 8, so yes |
| Union of two sets | a | b |
|
| Common items | a & b |
|
| Items in a but not in b | a & ~b |
Step by step: Granting, revoking, toggling and testing permissions. The animated player loads in your browser.
A set of n items has 2^n subsets, and they match the masks from 0 to 2^n - 1. A loop for mask in range(1 << n) visits every subset, and bit i of the mask says whether item i is in it. For 20 items that is 1,048,576 subsets, which is fast. For 31 items it is more than two billion.
The number of items a mask can hold depends on the language.
| Language | Items in one mask |
|---|---|
| Python | Any number: ints grow as needed |
| Java | 31 in an int for safe use, 63 in a long (bit 31 or 63 is the sign bit) |
| C++ | 32 in unsigned, 64 in unsigned long long |
| JavaScript | 31 in a bitwise number. Bitwise operators work on 32 bits, so a mask for item 32 or more breaks. Use BigInt, or several numbers |
Pick a problem, then step through it forwards and back. The columns being combined are outlined. In the permission problem, the bit that changes is outlined, and the names sit under the bits.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Each method keeps one fact true. Say the fact, and the correctness follows.
Each bit of an AND, OR or XOR result depends only on the two input bits in the same position, so columns never affect one another.
So you can check any result one column at a time, as the visualizer does. Shifts and addition do not have this property: a shift moves bits between columns, and addition carries.
For x above 0, x & (x - 1) clears only the lowest 1 bit, so the steps to reach 0 equal the number of 1 bits.
The loop ends because each step removes one 1 bit, and a number of at most 31 bits has at most 31 of them.
Bit i of a mask is 1 exactly when item i is in the set, so every set operation on item i touches only bit i.
Every set operation can then be written as an operator on whole masks, and the other items are never touched.
Counting 1 bits, one step for each 1 bit. This works for x of 0 or more.
def count_set_bits(x):
count = 0
# [1] Keep going while any 1 bit is left.
while x > 0:
# [2] x & (x - 1) clears the lowest 1 bit and changes no other bit.
x = x & (x - 1)
# [3] One step cleared one 1 bit, so the steps count the 1 bits.
count += 1
return countpublic int countSetBits(int x) {
int count = 0;
// [1] Keep going while any 1 bit is left.
while (x > 0) {
// [2] x & (x - 1) clears the lowest 1 bit and changes no other bit.
x = x & (x - 1);
// [3] One step cleared one 1 bit, so the steps count the 1 bits.
count++;
}
return count;
}int countSetBits(int x) {
int count = 0;
// [1] Keep going while any 1 bit is left.
while (x > 0) {
// [2] x & (x - 1) clears the lowest 1 bit and changes no other bit.
x = x & (x - 1);
// [3] One step cleared one 1 bit, so the steps count the 1 bits.
count++;
}
return count;
}function countSetBits(x) {
let count = 0;
// [1] Keep going while any 1 bit is left.
while (x > 0) {
// [2] x & (x - 1) clears the lowest 1 bit and changes no other bit.
x = x & (x - 1);
// [3] One step cleared one 1 bit, so the steps count the 1 bits.
count++;
}
return count;
}Exercise · Put it in order: One step for each 1 bit. Arrange the lines into a function that counts the 1 bits of a whole number that is 0 or more.
def count_set_bits(x):
count = 0
while x > 0:
x = x & (x - 1)
count += 1
return count
x = x - 1Setting and clearing flags in a mask. Each grant sets one bit and each revoke clears one bit.
def edit_flags(mask, grants, revokes):
# [1] Set each granted bit: OR with a 1 shifted to that place. Every other bit stays as it was.
for bit in grants:
mask = mask | (1 << bit)
# [2] Clear each revoked bit: AND with a mask that has every bit set except that one.
for bit in revokes:
mask = mask & ~(1 << bit)
# [3] Revokes run last, so a bit that is both granted and revoked ends up cleared.
return maskpublic int editFlags(int mask, int[] grants, int[] revokes) {
// [1] Set each granted bit: OR with a 1 shifted to that place. Every other bit stays as it was.
for (int bit : grants) {
mask = mask | (1 << bit);
}
// [2] Clear each revoked bit: AND with a mask that has every bit set except that one.
for (int bit : revokes) {
mask = mask & ~(1 << bit);
}
// [3] Revokes run last, so a bit that is both granted and revoked ends up cleared.
return mask;
}int editFlags(int mask, vector<int> grants, vector<int> revokes) {
// [1] Set each granted bit: OR with a 1 shifted to that place. Every other bit stays as it was.
for (int bit : grants) {
mask = mask | (1 << bit);
}
// [2] Clear each revoked bit: AND with a mask that has every bit set except that one.
for (int bit : revokes) {
mask = mask & ~(1 << bit);
}
// [3] Revokes run last, so a bit that is both granted and revoked ends up cleared.
return mask;
}function editFlags(mask, grants, revokes) {
// [1] Set each granted bit: OR with a 1 shifted to that place. Every other bit stays as it was.
for (const bit of grants) {
mask = mask | (1 << bit);
}
// [2] Clear each revoked bit: AND with a mask that has every bit set except that one.
for (const bit of revokes) {
mask = mask & ~(1 << bit);
}
// [3] Revokes run last, so a bit that is both granted and revoked ends up cleared.
return mask;
}The bits here are 0 to 30. Bit 31 of an int is the sign bit, and 1 << 31 is negative in Java and JavaScript. The OR and AND would still work there, but a test such as > 0 would not, as the mistakes section shows.
The XOR loop for the value with no pair is the same shape: start from 0, and single ^= value for each id. JavaScript's ^ works on 32-bit signed ints, so it is right for ids from -2^31 to 2^31 - 1. For ids of 2^31 or more it would silently cut them: 3000000000 ^ 0 is -1294967296. Use BigInt there.
Predict what happens
Q In Java, x = Integer.MIN_VALUE. The test (x & (x - 1)) == 0 without x > 0 says what?
Answer: B
Integer.MIN_VALUE is 1 followed by 31 zeros. Subtracting 1 wraps to 0 followed by 31 ones, and the AND of the two is 0. Java does not throw on int overflow, so the test wrongly passes unless you also check x > 0.
A fixed number of bits can hold only so many values. Overflow is a result that does not fit. What happens next depends on the language.
| Language | Whole numbers | What 2147483647 + 1 does |
|---|---|---|
| Python | int has no limit |
2147483648, exact |
| Java | int is 32 bits, long is 64 bits |
int wraps to -2147483648, with no error. Math.addExact throws ArithmeticException instead |
| C++ | int is 32 bits on common platforms, long long is at least 64 bits |
Undefined behaviour for a signed type. A compiler may assume it never happens. unsigned wraps and is defined |
| JavaScript | A Number is a 64-bit double. BigInt has no limit |
2147483648, exact. A Number is exact only up to 2^53 - 1, which is 9,007,199,254,740,991 |
Three facts about JavaScript follow from the table:
Number loses exactness past 2^53: 2 ** 53 + 1 === 2 ** 53 is true.Number to a 32-bit signed int first. So 5000000000 | 0 is 705032704, with no warning.BigInt is written 10n. It cannot be mixed with a Number, because 1n + 1 is a TypeError. It has >> but no >>>.Add 1 to the largest 32-bit int. Java wraps round with no error, Python and JavaScript keep the exact value, and C++ leaves it undefined.
Three more habits follow from this table:
long, long long) for any total that may pass about 2 billion.int * int is computed in int even when you assign it to a long. Write (long) a * b, not (long) (a * b).Math.abs(Integer.MIN_VALUE) is still negative in Java, because +2^31 does not fit.Modular arithmetic keeps only the remainder after division by a number m, the modulus. A clock is mod 12: 9 o'clock plus 5 hours is 2 o'clock. The rules for add, subtract and multiply let you reduce at every step instead of at the end.
| Rule | Why you need it |
|---|---|
(a + b) % m = ((a % m) + (b % m)) % m |
Adding two residues never passes 2m |
(a * b) % m = ((a % m) * (b % m)) % m |
The product of two residues is below m squared |
(a - b) % m can be negative in Java, C++ and JavaScript |
Use ((a - b) % m + m) % m |
| Division does not follow the same rule | Multiply by a modular inverse instead |
A counting problem such as "how many subsets" can have an answer with thousands of digits: 2^1000 has 302 digits. Judges avoid big numbers by asking for the answer modulo 1,000,000,007, which is 10^9 + 7. This modulus is used for three reasons:
m and a not a multiple of m, the inverse of a is a^(m-2) mod m.int.That is why the types matter. In Java, a * b % m with int a and int b overflows before % runs. Take a = b = 100000: the product is 10^10, which wraps to 1410065408 in a 32-bit int, and the program prints 410065401 where the answer is 999999937.
In JavaScript the product 1000000006 * 1000000006 is about 10^18, which a double cannot hold exactly, so the remainder comes out wrong. Use long, long long, or BigInt.
A JavaScript Number multiplies two residues exactly only when the modulus is at most 94,906,266, because 94,906,265 squared is below 2^53 and 94,906,266 squared is above it.
The same idea explains hashing. A hash table picks a bucket with hash % buckets. A lucky draw for n players picks position (seed * k) % n. Both need the result to be in 0 to n - 1, so a negative remainder from % has to be fixed first.
The sign of % for negative numbers differs. For -7 % 3:
| Language | Result | Rule |
|---|---|---|
| Python | 2 | The result has the sign of the divisor, so it is 0 to m - 1 |
| Java, C++, JavaScript | -1 | The result has the sign of the dividend |
Java also has Math.floorMod(-7, 3), which is 2. Integer division differs in the same way: -7 // 2 is -4 in Python, and -7 / 2 is -3 in Java and C++. JavaScript's -7 / 2 is -3.5, so use Math.trunc or Math.floor.
Predict what happens
Q In Java, int a = 3, b = 5, m = 7. What does (a - b) % m give?
Answer: B
3 - 5 is -2, and -2 % 7 is -2 in Java, C++ and JavaScript. Python gives 5. To get 0 to m - 1 everywhere, write ((a - b) % m + m) % m.
The greatest common divisor (gcd) of two numbers is the largest number that divides both. If you share 12 sweets and 18 sweets into bags of equal size, with none left over, the biggest bag you can use is gcd(12, 18) = 6.
Euclid's rule is gcd(a, b) = gcd(b, a mod b), and gcd(a, 0) = a. Take gcd(1071, 462):
| a | b | a mod b |
|---|---|---|
| 1071 | 462 | 147 |
| 462 | 147 | 21 |
| 147 | 21 | 0 |
The answer is 21, after 3 steps. The rule works because any number that divides both a and b also divides a - q * b, which is a mod b, and the reverse is true too. So the pair has the same common divisors after each step, and they get smaller.
The cost is small. When a ≥ b, a mod b is less than half of a: if b is at most half of a, the remainder is below b, and otherwise it is a - b. So every two steps at least halve the larger number.
For numbers below 2^31 the loop takes at most 45 steps. The worst pair is the neighbouring Fibonacci numbers 1,836,311,903 and 1,134,903,170, which take 44. Put the smaller one first and it takes one more, because the first step only swaps the two. Trying every divisor from the smaller number down would take up to 2 billion steps.
The least common multiple (lcm) is the smallest positive number that both divide. Two jobs that repeat every 4 days and every 6 days meet again on day lcm(4, 6) = 12. Since gcd * lcm = a * b, you get lcm(a, b) = a / gcd(a, b) * b.
Divide first, then multiply. The product a * b can overflow when the answer does not. For a = 60000 and b = 40000, the lcm is 120,000, but a * b is 2,400,000,000, which is -1894967296 in a Java int.
def lcm_of(a, b):
# [1] Start with a copy of each number, so that a and b are still there at the end.
x = a
y = b
# [2] Euclid: replace (x, y) by (y, x mod y) until y is 0. Then x is the gcd.
while y != 0:
x, y = y, x % y
# [3] Divide before you multiply: a divided by the gcd is exact, and the product stays as small as the answer.
return a // x * bpublic long lcmOf(int a, int b) {
// [1] Start with a copy of each number, so that a and b are still there at the end.
long x = a;
long y = b;
// [2] Euclid: replace (x, y) by (y, x mod y) until y is 0. Then x is the gcd.
while (y != 0) {
long rest = x % y;
x = y;
y = rest;
}
// [3] Divide before you multiply: a divided by the gcd is exact, and the product stays as small as the answer.
return a / x * b;
}long long lcmOf(int a, int b) {
// [1] Start with a copy of each number, so that a and b are still there at the end.
long long x = a;
long long y = b;
// [2] Euclid: replace (x, y) by (y, x mod y) until y is 0. Then x is the gcd.
while (y != 0) {
long long rest = x % y;
x = y;
y = rest;
}
// [3] Divide before you multiply: a divided by the gcd is exact, and the product stays as small as the answer.
return a / x * b;
}function lcmOf(a, b) {
// [1] Start with a copy of each number, so that a and b are still there at the end.
let x = a;
let y = b;
// [2] Euclid: replace (x, y) by (y, x mod y) until y is 0. Then x is the gcd.
while (y !== 0) {
const rest = x % y;
x = y;
y = rest;
}
// [3] Divide before you multiply: a divided by the gcd is exact, and the product stays as small as the answer.
return (a / x) * b;
}In JavaScript the product is a double, so an lcm above 2^53 is rounded: lcmOf(2147483647, 2147483646) gives 4611686011984937000, where the answer is 4611686011984936962. Use BigInt for an lcm that large.
This template is for a and b of 1 or more. With negative inputs, % can return a negative gcd in Java, C++ and JavaScript: Euclid on (4, -6) ends at -2. Take absolute values first, and remember Math.abs(Integer.MIN_VALUE) is still negative. Libraries do this for you:
math.gcd, and math.lcm from version 3.9.std::gcd and std::lcm in <numeric>.int gcd, only BigInteger.gcd.The gcd of a whole list is the fold gcd(gcd(a, b), c), and so on. The lcm of a list can grow fast, so reduce or use a 64-bit type with care.
A prime is a whole number above 1 whose only divisors are 1 and itself. To test one number n, try the divisors up to its square root, because a composite number has a divisor of at most that size. For n = 10^9 that is 31,622 tests.
To find all primes up to n, the sieve of Eratosthenes does it in bulk. Write down every number from 2 to n. Take the smallest number not crossed off, call it p, and cross off its multiples. Repeat for the next number that is left.
For n = 30, the primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29: ten of them. Only p of 2, 3 and 5 are needed, because the next prime, 7, has 7 x 7 = 49 above 30.
Two details make it fast. Start crossing at p * p, because a smaller multiple p * k with k < p has a smaller prime factor and was already crossed off. Stop when p * p is above n, because any composite number up to n has a factor of at most the square root of n.
The code returns the list of all primes up to n.
def primes_up_to(n):
if n < 2:
return []
# [1] Every number from 2 to n starts as a candidate. 0 and 1 are not primes.
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
p = 2
# [2] A composite number up to n has a factor of at most sqrt(n), so p only needs to reach it.
while p * p <= n:
if is_prime[p]:
# [3] Cross off the multiples of p from p * p. Smaller multiples were crossed off by smaller primes.
for multiple in range(p * p, n + 1, p):
is_prime[multiple] = False
p += 1
# [4] What is still a candidate is prime. Collect those numbers, in increasing order.
return [k for k in range(2, n + 1) if is_prime[k]]public int[] primesUpTo(int n) {
if (n < 2) {
return new int[0];
}
// [1] Every number from 2 to n starts as a candidate. 0 and 1 are not primes.
boolean[] isPrime = new boolean[n + 1];
java.util.Arrays.fill(isPrime, true);
isPrime[0] = false;
isPrime[1] = false;
// [2] A composite number up to n has a factor of at most sqrt(n), so p only needs to reach it.
for (long p = 2; p * p <= n; p++) {
if (isPrime[(int) p]) {
// [3] Cross off the multiples of p from p * p. Smaller multiples were crossed off by smaller primes.
for (long multiple = p * p; multiple <= n; multiple += p) {
isPrime[(int) multiple] = false;
}
}
}
// [4] What is still a candidate is prime. Collect those numbers, in increasing order.
java.util.List<Integer> found = new java.util.ArrayList<>();
for (int k = 2; k <= n; k++) {
if (isPrime[k]) {
found.add(k);
}
}
int[] out = new int[found.size()];
for (int i = 0; i < out.length; i++) {
out[i] = found.get(i);
}
return out;
}vector<int> primesUpTo(int n) {
if (n < 2) {
return {};
}
// [1] Every number from 2 to n starts as a candidate. 0 and 1 are not primes.
vector<char> isPrime(n + 1, 1);
isPrime[0] = 0;
isPrime[1] = 0;
// [2] A composite number up to n has a factor of at most sqrt(n), so p only needs to reach it.
for (long long p = 2; p * p <= n; p++) {
if (isPrime[p]) {
// [3] Cross off the multiples of p from p * p. Smaller multiples were crossed off by smaller primes.
for (long long multiple = p * p; multiple <= n; multiple += p) {
isPrime[multiple] = 0;
}
}
}
// [4] What is still a candidate is prime. Collect those numbers, in increasing order.
vector<int> found;
for (int k = 2; k <= n; k++) {
if (isPrime[k]) {
found.push_back(k);
}
}
return found;
}function primesUpTo(n) {
if (n < 2) {
return [];
}
// [1] Every number from 2 to n starts as a candidate. 0 and 1 are not primes.
const isPrime = new Uint8Array(n + 1).fill(1);
isPrime[0] = 0;
isPrime[1] = 0;
// [2] A composite number up to n has a factor of at most sqrt(n), so p only needs to reach it.
for (let p = 2; p * p <= n; p++) {
if (isPrime[p]) {
// [3] Cross off the multiples of p from p * p. Smaller multiples were crossed off by smaller primes.
for (let multiple = p * p; multiple <= n; multiple += p) {
isPrime[multiple] = 0;
}
}
}
// [4] What is still a candidate is prime. Collect those numbers, in increasing order.
const found = [];
for (let k = 2; k <= n; k++) {
if (isPrime[k]) {
found.push(k);
}
}
return found;
}Exercise · Find the bug: The square that is left in. This sieve should return every prime up to n. For some n it returns a composite number as well. Which line is wrong?
def primes_up_to(n):
if n < 2:
return []
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
p = 2
while p * p < n:
if is_prime[p]:
for multiple in range(p * p, n + 1, p):
is_prime[multiple] = False
p += 1
return [k for k in range(2, n + 1) if is_prime[k]]The sieve makes about n log log n crossings: n times the log of the log of n. The log of the log grows so slowly that this is only a little more than n, about 2 crossings for each number in practice. The code makes 2,122,048 crossings for n = 10^6 and 22,850,051 for n = 10^7. Testing each number up to 10^7 by trial division up to its square root takes about 1.7 billion divisions.
The memory is one flag for each number. A Java boolean[] and a C++ vector<char> use about one byte each, so 10^7 numbers take about 10 MB. A Python list of True and False uses 8 bytes for each entry on a 64-bit build, which is 80 MB, so a bytearray is better there.
The loop in the Java and C++ code uses a 64-bit p, because p * p for p of 46,341 or more passes the int limit. That only happens for n of 2,147,395,600 or more, where the flags alone take 2 GB, but the habit is free. The primes up to 10^7 number 664,579.
To compute x^e, multiplying x by itself e times needs e - 1 multiplications. For e = 10^9, that is a billion. Squaring uses the bits of e. Write e = 13 = 1101 in binary, so x^13 = x^8 * x^4 * x^1.
The powers x^1, x^2, x^4, x^8 come from squaring the last one, and you multiply in those that match a 1 bit.
| Bit of e | Power of x for this bit | In the result? | Result so far |
|---|---|---|---|
| 1 (lowest) | x^1 | yes | x |
| 0 | x^2 | no | x |
| 1 | x^4 | yes | x^5 |
| 1 | x^8 | yes | x^13 |
A number e has about log2(e) bits, so the loop runs that many times: 30 times for 10^9, and 60 for 10^18. Each pass does at most two multiplications. Under a modulus, reduce after each multiplication, and the numbers never pass m squared.
def power_mod(base, exp, mod):
# [1] Start the result at 1, and bring the base into 0 to mod - 1.
# Python's % is never negative, so no fix is needed here.
result = 1 % mod
power = base % mod
# [2] When the lowest bit of exp is 1, multiply this power of the base into the result.
while exp > 0:
if exp & 1:
result = result * power % mod
# [3] Square the base for the next bit, and drop the bit just used. Reduce after every multiply.
power = power * power % mod
exp >>= 1
return resultpublic int powerMod(int base, int exp, int mod) {
// [1] Start the result at 1, and bring the base into 0 to mod - 1.
// Add mod back, because % can be negative here, and use a long for the products.
long result = 1 % mod;
long power = ((base % (long) mod) + mod) % mod;
// [2] When the lowest bit of exp is 1, multiply this power of the base into the result.
while (exp > 0) {
if ((exp & 1) == 1) {
result = result * power % mod;
}
// [3] Square the base for the next bit, and drop the bit just used. Reduce after every multiply.
power = power * power % mod;
exp >>= 1;
}
return (int) result;
}int powerMod(int base, int exp, int mod) {
// [1] Start the result at 1, and bring the base into 0 to mod - 1.
// Add mod back, because % can be negative here, and use a long long for the products.
long long result = 1 % mod;
long long power = ((base % (long long) mod) + mod) % mod;
// [2] When the lowest bit of exp is 1, multiply this power of the base into the result.
while (exp > 0) {
if (exp & 1) {
result = result * power % mod;
}
// [3] Square the base for the next bit, and drop the bit just used. Reduce after every multiply.
power = power * power % mod;
exp >>= 1;
}
return (int) result;
}function powerMod(base, exp, mod) {
const m = BigInt(mod);
// [1] Start the result at 1, and bring the base into 0 to mod - 1.
// Add mod back, because % can be negative here, and use BigInt for the products.
let result = 1n % m;
let power = ((BigInt(base) % m) + m) % m;
let e = BigInt(exp);
// [2] When the lowest bit of exp is 1, multiply this power of the base into the result.
while (e > 0n) {
if ((e & 1n) === 1n) {
result = (result * power) % m;
}
// [3] Square the base for the next bit, and drop the bit just used. Reduce after every multiply.
power = (power * power) % m;
e >>= 1n;
}
return Number(result);
}The code takes exp of 0 or more and mod of 1 or more. It uses 1 % mod and not 1, so that mod = 1 gives 0, as it should. Python has pow(base, exp, mod) built in. Writing base ** exp % mod in Python builds the whole power first: 3 ** 100000000 has about 158 million bits, which is about 20 MB, before % runs.
Modular division uses this too. For a prime m, pow(a, m - 2, m) is the inverse of a: for m = 7 and a = 3, 3^5 mod 7 is 5, and 3 * 5 is 15, which is 1 mod 7.
Predict what happens
Q How many squaring steps does power_mod need for an exponent of 1,000,000,000?
Answer: C
1,000,000,000 is below 2^30, so it has 30 bits, and the loop runs once per bit. Each pass squares once and multiplies at most once, so under 60 multiplications in all.
Now write it yourself. In the chat app, a member's permissions are stored as one mask. The admin screen has to show them one by one, smallest first: a mask of 44 means the permissions worth 4, 8 and 32.
The lab has one function, split_mask(mask). It returns the list of single-bit values that add up to the mask, from smallest to largest.
Use the two tricks from the second beat: x & -x keeps the lowest 1 bit, and x & (x - 1) clears it. Here is a run with the mask 44, which is 101100.
| Step | mask before |
Lowest bit, mask & -mask |
List so far | mask after, mask & (mask - 1) |
|---|---|---|---|---|
| 1 | 44 (101100) |
4 | [4] | 40 (101000) |
| 2 | 40 (101000) |
8 | [4, 8] | 32 (100000) |
| 3 | 32 (100000) |
32 | [4, 8, 32] | 0 |
The mask is 0, so the loop stops. The answer is [4, 8, 32], and it took one step for each 1 bit.
Three rules keep it correct:
1 << i in Java or JavaScript. For i = 31, 1 << 31 is negative, and a comparison such as > 0 fails. The two tricks avoid the shift altogether.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Bit tricks | Euclid's gcd | Sieve | Squaring |
|---|---|---|---|---|
| Time | One step for a test, set or clear. A bit count takes one step for each 1 bit | At most 45 steps for numbers below 2^31 | About n log log n for all primes up to n | About log2 of the exponent steps |
| Memory | One number | One number | One flag for each number up to n | One number |
| Stops early? | A loop ends when x is 0 | Ends when the remainder is 0 | No, it crosses off to the square root of n | No, it reads every bit of the exponent |
| What goes wrong | Sign bit, shift counts, precedence | Negative inputs, a product that overflows | Memory for a large n | Overflow before the remainder |
Use a bitmask when there are at most 31 items (63 in a 64-bit type) and you need fast union, intersection and membership. To enumerate all subsets, keep to about 20 items, which is a million masks. Use XOR when pairs cancel, and x & (x - 1) when the count of 1 bits matters.
Use % m when an answer is too big to print, or when a value must land in a fixed range. Use Euclid whenever the question is about common divisors or repeating cycles. Use the sieve when you need many primes up to a known n, and squaring when an exponent is huge.
Do not use bit tricks only to look short. A readable set.contains(item) is better when the set is large, the items are not small numbers, or the code is not on a hot path.
Do not use a bitmask for more than 31 items in a Java int or a JavaScript number. Do not run a sieve for a single number: test divisors up to its square root. Do not call a power function in floating point (Math.pow, pow) when you need an exact big integer or a remainder.
x % 2 == 1 is the usual test for an odd number. For x = -3, Python gives -3 % 2 == 1, which is true. Java, C++ and JavaScript give -1, so the test is false and a negative odd number is called even.
Use x % 2 != 0, or the bit test (x & 1) == 1. In two's complement, bit 0 of -3 is 1 in every language.
Python says -3 mod 2 is 1, but Java, C++ and JavaScript say -1, so a test for 1 fails for negative odd numbers.
In C++, Java and JavaScript, == binds more tightly than &. So x & 1 == 0 means x & (1 == 0).
In Java that does not compile, because int & boolean is not allowed. In C++ and JavaScript it compiles. It computes x & 0, which is 0 for every x, so the test for an even number is false even for x = 4.
Python does not have this problem, because its & binds more tightly than ==. Write (x & 1) == 0 in all four.
(mask & (1 << 31)) > 0 looks like "is bit 31 set". In Java, take mask = 1 << 31. That value is -2147483648, and mask & (1 << 31) is -2147483648 too. It is not above 0, so the test says the bit is clear.
Write != 0. In JavaScript the same test fails for the same reason, and 1 << 32 is 1 and not 4294967296.
(a * b) % m with int a = 100000 and int b = 100000 and m = 1000000007. The product is 10^10, which wraps to 1410065408 in a Java int. The program prints 410065401, and the answer is 999999937.
In C++ the same signed overflow is undefined. Use (long long) a * b % m. In JavaScript, a double is exact only to 2^53, so for residues near 10^9 use BigInt.
(a - b) % m with a = 3, b = 5 and m = 7. Python gives 5. Java, C++ and JavaScript give -2, which is not a valid index, bucket or residue.
Write ((a - b) % m + m) % m. The same fix applies to a hash. Java's hashCode() can be negative, so hash % buckets can be negative, and the index -2 throws an exception.
a * b / gcd(a, b) for the lcm of a = 60000 and b = 40000. The product is 2,400,000,000, which wraps to -1894967296 in a Java int, so the lcm comes out negative, when the real answer is 120,000.
Divide first: a / gcd(a, b) * b, with the product in a 64-bit type. The division is exact, because the gcd divides a.
(x >> i) & 1, x | (1 << i), x & ~(1 << i) and x ^ (1 << i). Put brackets around every bit test.x & (x - 1) clears the lowest 1 bit. It counts bits, tests for a power of two (with x > 0), and XOR of all values leaves the one that has no pair.|, common items are &, and 1 << n gives the number of subsets. A Java int and a JavaScript bitwise number hold 31 items safely.Explain the methods in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Signed numbers
Q In 8-bit two's complement, which pattern is -1?
Answer: C
Flip the bits of 1 (00000001) to get 11111110, and add 1 to get 11111111. Read as unsigned it is 255. The pattern 10000000 is -128.
Checkpoint · Bit tricks
Q1/2 Which expression clears bit 3 of x and leaves the other bits alone?
Answer: C
~(1 << 3) is all 1 bits except bit 3. ANDing with it keeps every other bit and forces bit 3 to 0. The first option sets it, the second flips it, and the last keeps only that bit.
Q2/2 Starting from x = 44, how many times does x = x & (x - 1) run before x is 0?
Answer: D
44, 40, 32, 0: each step removes the lowest 1 bit, and 101100 has 1 bits worth 4, 8 and 32. The loop runs once for each 1 bit, not once for each place.
Checkpoint · Power of two and XOR
Q1/2 Which test says that any int x is a power of two?
Answer: B
A power of two has one 1 bit, so clearing it leaves 0. But 0 also gives (x & (x - 1)) == 0, and so does Integer.MIN_VALUE in Java, so x > 0 is needed. The last two test for an even number, and the last one also has a precedence bug.
Q2/2 What is 8 ^ 3 ^ 8 ^ 5 ^ 5?
Answer: D
8 ^ 8 is 0 and 5 ^ 5 is 0, and the order does not matter. What is left is 0 ^ 3, which is 3.
Checkpoint · Overflow and remainders
Q1/2 What does 2147483647 + 1 give?
Answer: B
A Java int wraps round silently. Python ints have no limit, and a JavaScript number is a double that holds 2147483648 exactly. In C++ a signed overflow is undefined, so no result is promised.
Q2/2 What does -7 % 3 give in Python and in Java?
Answer: C
Python's remainder has the sign of the divisor, so it is 2. Java's has the sign of the dividend, so it is -1. C++ and JavaScript behave like Java. Math.floorMod(-7, 3) gives 2 in Java.
Checkpoint · Modulus, gcd and the sieve
Q1/2 In Java, int a = 100000, int b = 100000 and m = 1000000007. What goes wrong with (a * b) % m?
Answer: C
The product is computed in int and wraps to 1410065408. Then % m gives 410065401 and not 999999937. Write (long) a * b % m instead.
Q2/2 Euclid's algorithm runs on 1071 and 462. Which list shows the remainders it computes?
Answer: B
1071 mod 462 is 147, 462 mod 147 is 21, and 147 mod 21 is 0. The last non-zero remainder, 21, is the gcd.
Checkpoint · The sieve
Q In a sieve of Eratosthenes for n = 100, where do you start crossing off the multiples of 7?
Answer: C
Smaller multiples such as 14, 21 and 35 have a smaller prime factor and were crossed off already. The loop on p runs while p * p is at most 100, so p reaches 10, and 7 is included.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.