Meta
Categories
 algebra (46)
 arithmetic (74)
 books (30)
 calculus (7)
 challenges (56)
 combinatorics (21)
 complex numbers (6)
 computation (72)
 convergence (9)
 counting (32)
 famous numbers (48)
 fibonacci (18)
 fractals (13)
 games (34)
 geometry (71)
 golden ratio (8)
 group theory (27)
 humor (6)
 induction (7)
 infinity (19)
 iteration (24)
 links (76)
 logic (9)
 meta (43)
 modular arithmetic (24)
 number theory (94)
 open problems (11)
 paradox (1)
 pascal's triangle (8)
 pattern (95)
 people (21)
 pictures (71)
 posts without words (29)
 primes (53)
 probability (6)
 programming (20)
 proof (83)
 puzzles (18)
 recursion (16)
 review (21)
 sequences (28)
 solutions (30)
 teaching (14)
 trig (3)
 Uncategorized (6)
 video (19)
Archives
 January 2019 (1)
 November 2018 (3)
 October 2018 (4)
 September 2018 (4)
 August 2018 (6)
 July 2018 (2)
 June 2018 (5)
 May 2018 (3)
 April 2018 (5)
 March 2018 (4)
 February 2018 (3)
 January 2018 (4)
 December 2017 (3)
 November 2017 (3)
 October 2017 (1)
 September 2017 (1)
 July 2017 (4)
 June 2017 (4)
 May 2017 (9)
 April 2017 (7)
 March 2017 (5)
 February 2017 (4)
 January 2017 (3)
 December 2016 (4)
 November 2016 (6)
 October 2016 (6)
 September 2016 (2)
 August 2016 (5)
 July 2016 (2)
 June 2016 (4)
 May 2016 (4)
 April 2016 (2)
 March 2016 (3)
 February 2016 (9)
 January 2016 (8)
 December 2015 (5)
 November 2015 (29)
 August 2015 (3)
 June 2015 (2)
 April 2015 (1)
 May 2014 (1)
 December 2013 (1)
 October 2013 (1)
 July 2013 (1)
 June 2013 (1)
 May 2013 (1)
 April 2013 (3)
 March 2013 (3)
 February 2013 (2)
 January 2013 (5)
 December 2012 (3)
 November 2012 (4)
 October 2012 (5)
 September 2012 (1)
 August 2012 (4)
 July 2012 (1)
 June 2012 (6)
 May 2012 (2)
 April 2012 (3)
 March 2012 (1)
 February 2012 (4)
 January 2012 (5)
 December 2011 (1)
 November 2011 (7)
 October 2011 (4)
 September 2011 (6)
 July 2011 (2)
 June 2011 (4)
 May 2011 (5)
 April 2011 (2)
 March 2011 (4)
 February 2011 (1)
 January 2011 (1)
 December 2010 (1)
 November 2010 (4)
 October 2010 (2)
 September 2010 (1)
 August 2010 (1)
 July 2010 (1)
 June 2010 (2)
 May 2010 (3)
 April 2010 (1)
 February 2010 (6)
 January 2010 (3)
 December 2009 (8)
 November 2009 (7)
 October 2009 (3)
 September 2009 (3)
 August 2009 (1)
 June 2009 (4)
 May 2009 (5)
 April 2009 (4)
 March 2009 (2)
 February 2009 (1)
 January 2009 (7)
 December 2008 (1)
 October 2008 (2)
 September 2008 (7)
 August 2008 (1)
 July 2008 (1)
 June 2008 (1)
 April 2008 (5)
 February 2008 (4)
 January 2008 (4)
 December 2007 (3)
 November 2007 (12)
 October 2007 (2)
 September 2007 (4)
 August 2007 (3)
 July 2007 (1)
 June 2007 (3)
 May 2007 (1)
 April 2007 (4)
 March 2007 (3)
 February 2007 (7)
 January 2007 (1)
 December 2006 (2)
 October 2006 (2)
 September 2006 (6)
 July 2006 (4)
 June 2006 (2)
 May 2006 (6)
 April 2006 (3)
 March 2006 (6)
The Fermat primality test and the GCD test
In my previous post we proved that if shares a nontrivial common factor with , then , and this in turn proves that is not prime (by Fermat’s Little Theorem).
But wait a minute, this is silly: if shares a common factor with , then we don’t need anything as complex as Fermat’s Little Theorem to figure out that is not prime! All we have to do is compute using the Euclidean Algorithm, and when we find out that the result isn’t , we can immediately conclude that isn’t prime since it has a nontrivial divisor.
So for comparison, let’s consider this (terrible!) primality test, call it the GCD test: given an we want to test, pick values of such that and compute for each one. If we find an for which , then is not prime.
This is terrible for several reasons. First, if we want this test to tell us for certain when is prime, we essentially have to try all the possible values of . We can optimize a bit by only trying —if has any nontrivial divisors we will be sure to find some that are under —but this doesn’t help all that much in the grand scheme of things. In fact, this GCD test is actually almost the same thing as trial division, where we try a bunch of different numbers to see whether they evenly divide . Both are essentially trying to find divisors of by bruteforce search.
So suppose instead that we are willing to live with some uncertainty, and we just try some fixed number of values for , and either conclude with certainty that is composite (if we happen to find an that shares a nontrivial factor with ), or report that it is probably prime. How bad can this be—or put another way, how many values of do we have to try so we can be “reasonably certain” that really is prime when the test says it is?
The answer is that it can be very bad indeed. Euler’s totient function counts the number of integers which are relatively prime to . So if is composite and we pick uniformly at random, there are choices which won’t reveal the fact that is composite, and approximately choices which do share a common factor with and hence do reveal the fact that it is composite.
So the question is, how big can be, relative to ? We would like it to be small—which would leave us with many opportunities to learn that is composite—but in fact it can be quite big. For example, , which is not much smaller than itself. This means that of the numbers less than share no factors in common with ; only of them share a factor. In fact, is big precisely when has just a few large prime factors, which intuitively is exactly when is most difficult to factor. For such there really is no acceptable number of ’s we can test with the GCD test in order to be reasonably sure that is prime—in the case of , for example, each we randomly pick has only a chance of sharing a common factor with ; and this can get arbitrarily bad as gets larger.
So remember we started down this path by showing that if we use the Fermat primality test, values of which share a common factor with will definitely reveal the compositeness of . But now we know that if we rely on only such values of , not only do we have a very small chance of discovering composite —no better than just using trial division—but more than that, actually using the Fermat test itself would be silly, since we should just use the simpler GCD test instead!
So if the Fermat primality test is worthwhile at all, it must be because there are other values of , which don’t share any common factors with , but nonetheless still reveal the fact that is composite since . So how many of those values of are there? Stay tuned!
Posted in computation, number theory, primes
Tagged Carmichael, Fermat, primality, test
Leave a comment
Making the Fermat primality test deterministic
Let’s recall Fermat’s Little Theorem:
If is prime and is an integer where , then .
Recall that we can turn this directly into a test for primality, called the Fermat primality test, as follows: given some number that we want to test for primality, pick an integer between and (say, at random), and compute . If the result is not equal to , then Fermat’s Little Theorem tells us that is definitely not prime. Repeat some fixed number of times . If we get every time, then report that is probably prime.
Making Fermat Deterministic
This “probably prime” business is a little annoying. Can we somehow turn this into a deterministic primality test? Well, for one thing, instead of just picking random values, what if we tested all ? (Yes, of course this would take way too long, but bear with me for a bit!) If they all yield when raised to the power, could still possibly be composite, or could we conclude it is definitely prime? Put another way, are there any composite numbers such that for all ?
It turns out that this would work: there do not exist composite numbers such that for all , so if we test all possible values of and we always get , then we can conclude with certainty that is prime. Let’s prove it!
Suppose is composite, and let be some number which shares a nontrivial common divisor with , that is, . If is composite then such an must exist; for example, we could just take to be one of ’s prime divisors. Now, I claim that can’t possibly be equivalent to . Let be the remainder when dividing by , that is, . Rearranging gives , which means that is divisible by , that is, for some integer . Rearranging this again, we get . But by our assumption, and are both divisible by , and hence must be divisible by —but that means must be divisible by as well. Since we assumed that and have a nontrivial common factor, that is, , we conclude that too, that is, .
So we now know that any number which shares a common factor with will definitely reveal the fact that is composite. How many (or how few) such could there be? And what about other values of , which don’t share a factor with —how many of them might also reveal the fact that is composite? We’ll tackle these questions in my next post!
Posted in computation, number theory, primes
Tagged deterministic, Fermat, primality, test
1 Comment
The wizard’s rational puzzle (solutions, part 2)
At long last, here is the solution I had in mind for the Wizard’s rational puzzle. Recall that the goal is to figure out the numerator and denominator of a secret rational number, if all we are allowed to do is reciprocate, add, subtract, multiply, and compare.
 Make sure the rational is greater than (reciprocating it if necessary).
 Repeatedly subtract from it until it becomes less than .
 At this point if it is equal to you can stop; otherwise, reciprocate it (making the result greater than again) and repeat the whole process.
Given the exact sequence of operations you did to reduce the rational to zero, you can easily reverse them to reconstruct the original rational. For example, suppose you had to subtract 1 three times, then reciprocate, then subtract 1 five times, reciprocate, then subtract 1 two more times. This gives us the equation
or, inverting everything to solve for ,
.
This clearly gives the right answer; the only question is whether it will stop after a finite amount of time. But it does, since every time we subtract 1 we are making the numerator smaller without changing the denominator, and reciprocating just switches the numerator and denominator without making them bigger. Also, if we had a number less than 1 and reciprocate it, the result will definitely be bigger than 1, at which point we can subtract 1 from it at least once, and hence we cannot get stuck reciprocating repeatedly without doing any subtracting. Since we have two positive integers which are either staying the same or getting smaller on each step, the process must eventually stop.
There are several equivalent ways to think about what is going on here:

One way to think about this—made clear by the expression for in the example above—is that we are building up the continued fraction expansion for .

Another way to think about it is that we are running the Euclidean Algorithm on ’s numerator and denominator. Of course the Euclidean Algorithm is typically used to find the greatest common divisor of two numbers, and if we imagine to be in lowest terms then of course the gcd of its numerator and denominator will be 1, so finding the gcd doesn’t tell us anything in and of itself. The point is, however, that the exact sequence of steps taken by the Euclidean Algorithm is unique for each relatively prime pair , and so we can use the sequence of steps to reverseengineer what and must have been in the first place.

Yet another way, closely related to the previous, is to imagine that we are finding our way up the CalkinWilf tree step by step. Recall that the CalkinWilf tree is the infinite binary tree of positive rationals where the root is and each node has as its left child and as its right child. Each rational appears at a unique location in the tree, so the sequence of upwards steps taken from to the root allows us to reconstruct the original .
More specifically, if we have a number bigger than , it must be of the form for some and , i.e. it is a right child in the CalkinWilf tree. Subtracting one from yields , so it corresponds to taking one step up and to the left in the CalkinWilf tree. When we reach a number less than , it means that node is a left child, so we cannot take another step up and to the left. Reciprocating corresponds to mirroring the entire tree leftright, and then we can continue taking steps up and to the left.
So how long does this take? Moving up one level in the CalkinWilf tree takes at worst operations: one subtraction, two comparisons, and a reciprocate. (We have to do two comparisons because when we find out that a number is less than one, we have to also check if it is greater than 0 to see whether we should reciprocate or stop.) On the other hand, the best case takes only two operations (a subtraction and a comparison, if the result is still greater than one). The worst case for a given depth in the CW tree would be if we start with the ratio of two consecutive Fibonacci numbers, since we would have to reciprocate after doing only one subtraction at every single step (try it!).
There’s also another fun thing we can do to speed things up. Instead of just subtracting repeatedly, we can use a sort of binary search instead. That is, we can first create cubes containing powers of two (in practice we can just create them on the fly as needed). Then given a number , we first find the smallest power of two such that is less (by computing , then , then , then , … and checking each time until we find the first such that ), and then we do a binary search on the interval to find the smallest such that (in practice this just means adding or subtracting the next smaller power of two at each step, depending on whether the previous step was less than or greater than 1). Not counting the operations needed to create the cubes with the powers of 2 in the first place (since we can reuse them many times, and in any case it takes only one operation per power of two), this would take about addition and subtraction operations. One might worry that this would be slightly slower for small values of ; however, I think (but have not fully worked out the details) that this will actually never require more operations than the naive subtraction method; I will leave this as an exercise. Of course, for larger this is clearly going to be a big win, since is much smaller than .
Of course, if the wizard had provided a machine that could perform a “floor” operation, we could make this even more efficient: instead of subtracting until finding a result less than , we could just compute . This is like being able to jump as far up and to the left as possible in the CalkinWilf tree using only two operations. (Unsurprisingly, the floor function plays a key role in the algorithm for generating the CalkinWilf sequence.) I actually had this in the original version of the puzzle, but took it out when I realized that it was not necessary, and slightly more interesting to do without!
Several commenters mentioned using the SternBrocot tree to search for the secret rational. It’s probably a topic for another blog post, but briefly, the idea is to keep track of four integers , , , and representing the rational numbers and . We start with and (representing ) and , (, representing “infinity”). We maintain the invariant that , that is, we maintain and as the endpoints of an interval that contains the secret rational . At each step we compute the mediant , which is guaranteed to lie in between and (exercise: prove this!), and check whether it is equal to the secret rational. If not, we either set or , depending on whether the secret rational is greater or less than , respectively. Unlike a simple binary search (which can only find rationals with a denominator that is a power of two in finite time), this is guaranteed to terminate in a finite amount of time; every rational can be obtained after a finite number of successive steps of taking the mediant.
So how long does it take? It turns out that the SternBrocot tree and the CalkinWilf tree have all the same rationals on each level, but in a different order^{1}, so the two methods are easy to compare. The proposed SternBrocot method moves down the tree one level each step, and it needs four five operations for each step (two additions to form the mediant, one division to turn the pair of integers representing the mediant into a rational number, and then two comparisons to find out whether the mediant is less than, equal to, or greater than the target number). Unless there is a more clever way to do this that I missed, it seems my method is a clear win: for a rational on level of the SternBrocot or CalkinWilf trees, the iterated mediant algorithm always needs exactly operations, whereas for my algorithm is only a worst case (for a ratio of consecutive Fibonacci numbers), but in many cases it does better (much better for rationals with large entries in their continued fraction expansion, which we can skip past in logarithmic time).

Each is a bitreversal permutation of the other.↩
Posted in arithmetic, challenges, logic, programming, puzzles, solutions
Tagged arithmetic, binary, denominator, Euclidean, gcd, logarithm, numerator, puzzle, rational, search, wizard
Leave a comment
The wizard’s rational puzzle (solutions, part 1)
About two and a half months ago I posted a challenge involving a sadistic math wizard, metal cubes containing rational numbers, and a room full of strange machines. I’ve been remiss in following up with some solutions. (Go read the first post and think about it before reading on if you haven’t already!)
I had fun creating an elaborate setup to frame the puzzle, but as you probably figured out, really the puzzle comes down to this: is it possible to figure out the numerator and denominator of an unknown positive rational number, if you are only allowed to take reciprocals, add, subtract, multiply, and test whether one number is less than another?
There are many ways to solve this. First, a few preliminary ideas which many commenters picked up on:
 The reciprocal of the reciprocal of is again—that is, —so we can use the reciprocator machine as a copying machine, in order to create multiple cubes with the same value.
 We can also multiply any by its reciprocal to create , that is, we can make a cube which we know contains the number . We can also make a cube containing by making a copy of any number and then subtracting it from itself.
 We can also use the reciprocator machine, in conjunction with multiplication, to implement division: to compute we reciprocate and then multiply the result by , since .
 We can use copies of the number , along with operations like addition and multiplication, to create a cube containing any positive integer we want. (We can also use subtraction to create any negative integer.) We can then divide such integers to create any rational number we want.
 We can test whether any two cubes contain equal numbers by putting them into the lessthan comparator twice, once in each order. If the machine says “true” one way and “false” the other way, then one number is really less than the other. If it says “false” both ways, then the numbers must be equal, since this is the only situation in which both and are false.^{1}
Given these preliminaries, the simplest method, put forth originally by Eric Burgess, is to methodically list all the positive rational numbers (creating each one by building up its numerator and denominator out of copies of the number ) and test each one to see whether it is equal to the wizard’s number. Since the rational numbers are countable, we can list them in such a way that every rational number appears at a finite position. This means that no matter what the wizard’s number is, after some finite amount of time we will encounter it in our list. (One very nice such list we might consider is the CalkinWilf order , …)
However, this could of course take a long time. For example, suppose the wizard has chosen . It turns out that this is the 4,285,192nd rational in the CalkinWilf order. Even if we can construct and test one rational number every 20 minutes (which actually seems overly optimistic, more on this later), it would still take us over years (with no breaks for sleeping or eating, and did you notice the wizard didn’t seem to provide a bathroom for us to use?). So we have to ask: is there a faster way?

If the machine says “true” both ways, then you should probably start thinking about deconstructing the machines and using the parts to build some kind of weapon or clever escape device.↩
Posted in arithmetic, challenges, logic, programming, puzzles, solutions
Tagged arithmetic, denominator, Euclidean, gcd, logarithm, numerator, puzzle, rational, wizard
3 Comments
Quickly recognizing primes less than 1000: memorizing exceptional composites
In my previous post I wrote about a procedure for testing the primality of any number less than :

Test for divisibility by all primes up to , and also . (In practice I test for 2 and 5 first, which is pretty much automatic; then for 3 and 11, which both involve adding and subtracting digits; then 7 and 19, which both involve multiplying the final digit by two and either subtracting (7) or adding (19); and last I test for 13.)

Check if the number is one of a memorized list of 18 composites less than which are not divisible by either or any prime . (In practice, of course, I do this check first, before doing any divisibility tests.)
How fast is it?
Using this method, presented with a random number from 11000 not divisible by 2 or 5 (I exclude those because I can pretty much tell they are not prime instantaneously, and I think it makes for a more interesting measurement to exclude them), right now it takes me on average 15 seconds to determine whether such a number is prime or not. Of course the variance is huge: numbers that are divisible by 3 I can identify in a second; for numbers that are actually prime, it can take me something like 40 seconds to run through all the divisibility tests in my head. I expect with practice I’ll get faster.
I’m still interested in exploring other methods as well, but figured this is something relatively simple that can provide a good baseline for comparison!
Memorizing exceptional composites
For the rest of the post I want to talk about how I memorized the list of exceptional composites. Here’s the list again, this time with prime factorizations given:
That looks like a lot of stuff to memorize. And it would be, if you tried to memorize it as a bunch of individual, disconnected facts. But fortunately we can do better! Human brains are good at remembering sequences and stories. So we’re going to look at the numbers in order and tell ourselves stories about them. The better we get to know them and their relationships the easier they are to remember!
289, 391, 493
There is only one exceptional composite in each of the 200’s, 300’s, and 400’s, namely, 289, 391, and 493. What strikes one immediately about these numbers is that each is exactly 102 more than the previous. Is this a coincidence?
Of course not! It is actually due to the fact that . Each of these numbers is a product of with some other prime, and the second prime increases by every time. That is, , then , and . Of course adding 6 to a prime doesn’t always get us another prime—but it works surprisingly often for smaller primes. And every prime besides 2 and 3 is either one more than a multiple of 6, or one less. So if we start with 5 and 7 and keep adding 6, we will definitely hit all the primes.
This sequence of multiples of 17 starts from , and if we continue it further we see that it contains several more numbers from our exceptional set as well:
What about if we start with and keep adding ?
This sequence yields three of our exceptional composites, and quite a few others which in theory we can rule out with our divisibility tests but are probably worth knowing anyway (, , , ).
527, 529, 629, 667, 697
There are only two exceptional composites in the 500’s, and they are twins: 527 and 529. 527 we have already seen: it shows up in the sequence of multiples of 17 that begins with . On the other hand 529 is .
The next exceptional composite is 629, the next multiple of 17 in the sequence after 527. Of course it is also exactly 100 bigger than 529. I personally find the sequence 527, 529, 629 to be quite memorable.
Next is , which is the closest integer to twothirds of 1000. If you know that , then 667 is also easy to remember for two reasons: it has the same digits as 676 but with the 7 and 6 reversed, and it is exactly 9 less than 676, and hence it is .
The last exceptional composite in the 600’s is 697, which is from the sequence of multiples of that started with 289, 391, 493 (595 is skipped because it is obviously a multiple of 5).
713, 731, 799, 841, 851, 899
Next come a pair of twins, a 99, then another pair of twins, then another 99! 713 and 731 are twins because they have the same digits, with the 1 and 3 reversed. 731 we have already seen: it is from the same 17sequence as 527 and 629. 713 is . 799 is again from the 17sequence beginning with 289.
841 and 851 are twins because they have the same digits except the 4 and the 5, which are consecutive. 841 is , and 851 is . Finally we have 899 which is .
901, 943, 961, 989
I haven’t thought of a nice story to tell about these—I think of the last three as sort of “sporadic”, but there’s only three of them so it’s not that hard. Someone else could probably come up with a nice mnemonic.
901 in any case is not too hard to remember because it’s a twin with 899, and it’s also the end of the 17sequence that started with 289.
943 is . It’s , but unlike some of the other differences of squares I’ve highlighted, I doubt this will actually help me remember it.
961 is . I think it’s cute that , , and are all perfect squares.
Last but not least, . If you happen to know that (I sure don’t!), then this is easy to remember as .
Once again
Repetition helps too, so let’s recite: it starts with , then continues by 102s: 391, 493. After that the twins 527, 529, followed by 629; then 667 and 697. Then two sets of twins each with its 99: 713, 731, 799; 841, 851, 899; then 901 to come after 899, and then the three sporadic values: 943, 961, 989!
Posted in arithmetic, computation, primes
Tagged 1000, algorithm, composite, exception, memorize, prime, recognize, test
Leave a comment