Further Information

Robin Nixon
Bestselling author of over 20 books and hundreds of magazine articles.

Recent posts
My books
Learning PHP, MySQL, JavaScript & CSS
The building dynamic websites bestselling blockbuster (new 3^{rd} edition out soon!)
Web Developer's Cookbook
Similar content to all three of my Plugin... books, but greater value in a single title
HTML5 For iOS And Android
Create apps with simple web technologies for selling in the app stores
Plugin PHP
100 cookbook recipes to save you reinventing the wheel  with free example downloadable code
Plugin JavaScript
100 cookbook recipes to save you reinventing the wheel  with free example downloadable code
Plugin CSS
100 cookbook recipes to save you reinventing the wheel  with free example downloadable code
The PC Companion
Packed with tips & tricks for your MSDos PC (Published in the '90s, before Windows)
The Amstrad Notepad Advanced User Guide
The definitive manual for the 1990s Amstrad computer
Ubuntu: Up and Running
Everything you need to know about using and configuring the Ubuntu OS
Yes I Can!
Using visualization techniques to help you achieve many more of your desires and goals in life
Creative Visualization For Dummies
The secret to getting exactly what you want from life using simple visualizations
The Caverns of Eden
A thoughtprovoking collection of SF short stories plus a mini novella (Kindle eBook)
HTML5 para iOS y Android
Spanish translation of my book HTML5 for iOS and Android
Primes, Pseudo Primes, And Yet More Primes!
It’s possible to tell whether or not a number is prime in a number of ways. You can crunch through all possible factors of a number until you have a definitive result (which can take an exceedingly long time for very large numbers), or you can use a formula to return a very high level of probability about whether a number is prime. Recently I’ve been looking into both these methods.
In this post:
 How to create huge arrays of primes quickly using JavaScript
 Graphically displaying and animating prime numbers
 How to test for the probability of primality (Fermat’s Little Theorem)
 Numbers that resist these tests (Pseudo Primes and Carmichael Numbers)
 How to overcome this resistance
Finding Primes With JavaScript
At its simplest, to find all prime numbers between 1 and n in a language such as JavaScript, you can use code like this:
function getprimes(n) { var p = [] for (var j = 1 ; j < n ; ++j) if (isprime(j)) p.push(j) return p } function isprime(n) { for (var j = 2 ; j <= Math.sqrt(n) ; ++j) if (n % j == 0) return false return true }
The first function builds an array of prime numbers, which it returns in the array p[] by calling the second function to test all values of n for primality, up to the square root of n. The square root of n is chosen because all factors come in pairs and we only need to check the lowest of each pair. So (for example) the number 64 has the pair of primes 8 and 8, so you can clearly see that, therefore, the square root of a number is the largest that the smaller of a pair of primes can be.
It is possible to improve on code such as this because we know that all composite (nonprime) numbers can be created with a pair of prime factors. Therefore the previous code can be updated to only test for prime factors, like this (with the modifications shown in blue):
function getprimes(n) { var p = [] for (var j = 1 ; j < n ; ++j) if (isprime(p, j)) p.push(j) return p } function isprime(p, n) { for (var j = 1 ; p[j] <= Math.sqrt(n) ; ++j) if (n % p[j] == 0) return false return true }
The second function is also given access to the array p[] by adding it as an additional argument, so that it can look up previously determined prime numbers for use in its primality tests.
Now if, for example, the number being tested is 36, instead of checking possible factors 2, 3, 4, 5, and 6 (the square root of 36), only the values, 2,3, and 5 will be tested since they are the only primes numbers equal to or less than 6. This has saved two tests (4 and 6). And the bigger the number, the more tests you save until you can ignore about 5 in every 6 or so.
Indeed, you can also improve the main loop by ignoring all even numbers plus those that are divisible by 5, like this (with updates in blue):
function getprimes(n) { var p = [1, 2] for (var j = 3 ; j < n ; j += 2) if (j == 5  j % 5 != 0 && isprime(p, j)) p.push(j) return p } function isprime(p, n) { for (var j = 1 ; p[j] <= Math.sqrt(n) ; ++j) if (n % p[j] == 0) return false return true } }
In this version of the function, the p[] array is now prepopulated with the values 1 and 2 since they work slightly differently to the others, so they are handinserted. Then the loop starts at the number 3, with the (other unusual) number 5 accepted, but not any other multiples of 5. And now the code is fairly efficient, except that the square root function is not optimized for this particular use, and so a faster version of the inner function would be to remove the expression p[j] <= Math.sqrt(n), replacing it with p[j] * p[j] <= n.
You can now call this function with the following command (for example) to return the prime numbers up to 100, which will then be displayed in the current browser document:
document.write(getprimes(100))
The result of this command will be as follows, and I have tested it on an i7 PC with values of up to 10 million (which are calculated in about a second), and 100 million (which takes around 9 seconds):
1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
The PrimeDancer Web App
My new web app, PrimeDancer.com uses the preceding code to generate the primes it displays and animates. It’s a vastly improved and speeded up version of my earlier prime spiral animator, which now uses simple sliders to adjust the speed, direction, and zoom. It also lets you click in the animation to detect all the numbers in a sequence of a spiral arm, or use the sliders on the left to find them. When running the program looks like this, and I think you’ll find it rather fun to play with:
I find it fascinating (and quite relaxing) to watch all the possible patterns resulting from the distances between potential plot points on the spiral being slightly changed with each frame. What happens is that, for example, all the even numbers often reveal themselves as spiral gaps, but then so do multiples of three, four, five, and all the way up, as and when they are lined up above above each other in each turn of the spiral.
What’s more you can see multiple gaps at a time causing ‘interference’ patterns, and a tremendous amount of complexity reveals itself. One of my first theories was that where a spiral arms was particularly flush with pixels, it might be possible to follow that arm out like a rich vein of coal. Indeed when I did this it was the case, but only for a while. The further out you go the more the ratio of primes to composites returns back to the norm. Still, as you’ll see, there are other ways of finding seams of primes.
So this app is probably now more of a toy than a maths experiment that will yield new information, but I think it’s unique, and primes have never been displayed in quite such an interesting and dynamic manner before.
Continuing The Search For Prime Numbers
But why all this tinkering in the first place, you might ask? Well, things like Internet security rest on the employment of incredibly large prime numbers, so any new discoveries in this area could lead either to new, more powerful encryption systems, the cracking of current techniques, or even both. So it’s a fun (and potentially profitable) area to study.
The trouble is that (fast as it is), this type of code will never be good enough to identify enormous prime numbers quickly enough for improving (or hindering) ecommerce and private communications (even when written in compiled C or handcoded assembly language).
A Better Way to Test For Primality
Thankfully, though, there’s a better way (in fact there are several of them), the first of which was invented (or perhaps discovered) all the way back in the 1600s by the mathematician Fermat (yes, he of the famous Last Theorem). What is less known is that Fermat also came up with what is called his Little Theorem, in which the primality of a number can be predicted with a very high rate of probability by selecting what is termed a coprime number, and then raising this coprime to the power of the number to be tested. The coprime number can be any integer less than the one being tested, and need not be prime.
So, for example, to test the number 7, you could choose the coprime base value of 4 and raise it to the power of 7 (which is 4 × 4 × 4 × 4 × 4 × 4 × 4). If you can then subtract the coprime from this result such that the final result is exactly divisible by the number being tested, then the number could well be prime. It looks like this: (4^{7} – 4) / 7. Or like this in JavaScript:
if ((Math.pow(4, 7)  4) % 7 == 0) document.write('Possibly prime')
In this code, the % instruction divides by 7 and returns only the remainder (modulus) of the operation. So if the result is zero there was no remainder and so the the test is passed. If, however, there is a remainder then the number is definitely composite.
The Problem With Pseudo Primes
Interestingly, when applying Fermat’s little theorem, a few very strange numbers crop up which look very much like prime numbers to it, but they aren’t – and so they are given the title pseudo primes.
Some examples of Fermat’s pseudo primes include the numbers 341, 561, 645, 1105, 1387, and 1629. Actually there’s an infinite number of them, but you can see that they are fairly uncommon.
However, by changing the coprime used in the theorem to a different base number, and rerunning the test, you can almost always weed out these pseudo primes to narrow down your certainty.
The Resistant Carmichael Numbers
But you can only narrow down to an extent, because a subset of these pseudo primes (known as the Carmichael numbers after the mathematician who discovered the first one), resist the Fermat Little Theorem test in every base you choose:
In number theory, a Carmichael number is a composite number
n which satisfies the modular arithmetic congruence relation:
b ^{n} ≡ b (mod n) for all integers 1 < b < n – Wikipedia
This set of numbers includes 561, 1105, and 1721, and has an even rarer occurrence (only about 1 in 2.5 million). Nevertheless, these numbers are also infinite and are a considerable nuisance to cryptographers, who have now developed some very advanced mathematics to deal with this issue.
Before moving on to looking more deeply at these pseudo primes, though, let’s take a moment to write a program to simply map all prime and composite numbers onto a spiral, in a simpler version of my PrimeDancer App, like this:
<canvas id='canvas' width='630' height='630'></canvas> <script> var E = document.getElementById('canvas'), C = E.getContext('2d'), P = getprimes(1024), j, x, y for (j = 1 ; j < 1024 ; ++j) { x = 315 + Math.sin(j) * j * .3 y = 315 + Math.cos(j) * j * .3 if (isprime(P, j)) C.fillStyle = '#00f' else C.fillStyle = '#faa' C.fillRect(x, y, 2, 2) } </script>
This code uses a 630 × 630 pixel HTML5 canvas, onto which the first 1024 numbers are plotted by simply calculating the sine and cosine of of each number to rotate it a distance according to its size. Each consecutive number is then plotted slightly further out from the center of the canvas in either a salmony color for composites, or in blue for prime numbers.
This code obviously includes some HTML and the getprimes() function from earlier, but these are not shown. The result of running this program, which you can test for yourself here, is shown below:
The Chinese Hypothesis
Now let’s have some fun and slightly modify this code to enforce a variation of Fermat’s Little Theorem (known as the Chinese Hypotheses) on all these plot points, like this (with the changes highlighted in blue):
x = 315 + Math.sin((Math.pow(2, j) % j) * j * .3 y = 315 + Math.cos((Math.pow(2, j) % j) * j * .3
This time when you run the program the various plot point rotations are first vastly increased in size, and then restrained back again, causing spokes of point clustering around the circle. The result looks like this, which (for want of another word) I’ll call a Chinese Spiral:
Holy cow Batman. See how those primes just lined right up for us? And, interestingly, how many of the composites tried to also get in on the act along a number of other arms too (and many didn’t, which is also interesting). What happened is that the primes got in an orderly line because the expression used returned a modulus of 2 for every one.
Unfortunately, though, the Chinese Hypothesis also suffers from the pseudo prime problem. Let me illustrate this by running all the numbers from 1 to 1024 through the Chinese Hypothesis
for (j = 0 ; j < 1024 ; ++j) if (Math.pow(2, j) % j == 2) if (!isprime(P, j)) document.write(j + ' is pseudo prime<br>')
When you run this code the result is as follows:
341 is pseudo prime
561 is pseudo prime
645 is pseudo prime
Aha – we have found Fermat’s first three pseudo primes, and also the first Carmichael number (561). OK, so let’s tighten up the code a little and use the trick Fermat described, of testing using one or more additional bases, like this (with the change highlighted in blue):
for (j = 0 ; j < 1024 ; ++j)
if (Math.pow(2, j) % j == 2 && Math.pow(2, j) % j == 2)
if (!isprime(P, j))
document.write(j + ' is pseudo prime<br>')
Now when you run this code, no pseudo primes are returned – all prime numbers up to 1024 are successfully recognized, as confirmed by the isprime() test. I’d like to take this example further, but the limit of JavaScript’s Math library is reached at powers of 1024. So that will have to wait until I’ve written (or borrowed) a library for dealing with exceptionally large numbers.
A Possible New Angle?
But what I find interesting is that I thought the Carmichael numbers were supposed to be resistant to all base coprimes supplied to Fermat’s Little Theorem. But it seems that by using the Chinese Hypothesis variant with a different base, you can weed out (at least some of) the Carmichael numbers. Any mathematicians care to investigate this – it could possibly be significant?
Anyway, that’s enough messing around with primes for the moment – I have to get back to recording the videos for my new CSS book due for publication by McGrawHill in January. But I’d welcome distractions in the meantime if you have any ideas or thoughts to share in the comments :)
Posted in Articles, Features, Observations
Leave a comment
Animals are warm blooded because chocolate
Actually, because fat, to be more precise. As longtime readers will probably know I have so far lost over 50 pounds and reversed prediabetes by eating a ketogenic diet, in which carbohydrates are kept to a minimum, replaced with greater amounts of fat. This is the diet that Dr Atkins first made famous, but which is nowadays more likely to be called Paleo.
Anyway, after a trip to the London Natural History Museum this weekend, I got to thinking about why humans (and all mammals) are warm blooded. According to Wikipedia it may be because it helps us to fight of fungal infections.
Biologists agree that being warm blooded also helps us keep mobile in the cold – so it would have been a survival trait during ice ages. But being warm blooded requires a far greater intake of energy compared to a cold blooded creature, so there must be more to it than that for evolution to have forced this greater requirement for food on us.
Or was it maybe the other way around? For example, why is it that most warm blooded animals have temperatures just warm enough to melt chocolate, or many other fats that are solid at room temperature? Could it be that the ability to properly digest fat was a survival trait, because creatures that were warmer could better liquify this fat and process the energy more quickly and efficiently?
Therefore, did warm blooded animals continue to evolve higher and higher temperatures until just past the point at which they could eat solid fats, and keep them liquid during the digestion process – and no further, because higher temperatures would be wasteful of food, having no other purpose?
This would explain why the body temperatures of warm blooded animals are all similar, and not much higher than they are – they are just sufficiently warm to digest solid fats in the most efficient manner, as you will know if you’ve ever placed a piece of chocolate on your tongue and felt it melt – or even in your hands if you keep it there too long.
Is this, then, yet another indication that human beings evolved to eat fat as our main food source, and that carbohydrates in plentiful quantities are a modern product that our bodies are simply not yet adapted to deal with, other than to store carbs as fat – which is what we have done for millennia to store energy for the winter?
So, there you have my latest theory: People are warm blooded because chocolate :)
Posted in Articles, Observations
Leave a comment
Dancing With Bits
Following on from my recent mathematical investigations into infinities and prime numbers, I’ve branched out into playing with irrational numbers such as the square root of 2, e, and π – numbers whose fractional part is infinite – attempting to create new methods of detecting any hidden patterns in them.
So far, I haven’t had much luck, but then it’s early days and I didn’t expect to discover anything so quickly – and at my first attempt. However, I have come up with some fascinating results showing both the tremendous ‘chaos’ achievable from simple strings of binary digits, and an enormous amount of unexpected and complex symmetry too.
When I decided to look into irrational numbers the first big decision I made was to ignore base 10 or any other base higher than 2 because, it seemed to me, that binary is the fundamental base, and if any patterns are to be found they are mostly likely to be discovered in that base. I could be wrong, though, but I asked myself why would the universe choose to hide its wonders only within a base 10 number system? Well, you have to draw the line somewhere, but maybe later on I can start moving up the bases and seeing if anything different emerges.
Anyway, with that choice made I then set about converting a range of irrational numbers to binary, and started thinking about how I was going look for patterns in them. Obviously, the way numbers that follow a decimal (or binary) point work, is that each sequential digit is a factor of the base smaller than the previous one
In decimal the digits after the point are 10ths, then 100ths, then 1000ths and so forth, while in binary they are halfs, quarters, eighths, and so on. Therefore, to examine these sequences of numbers for patterns in any meaningful way, the relationships of scale between each binary digit (bit) to the ones before and after it needed to be taken into account.
But with fractional numbers scaling down in size so quickly, any visualization would rapidly dwindle down in size, so I needed to find another way of giving a relationship to the numbers, and decided to construct a model in which each bit is linked to the next by a line, and I would use different movement values to represent scale. However, because all lines would otherwise be the same length, there would be little indication of bit values themselves (or at the most, lines of only two different lengths for the digits 0 and 1). So I chose to make the lines longer whenever strings of two or more of a bit appeared in sequence – the longer the sequence, the longer the line.
Then, to indicate how the lines relate to each other, I chose to rotate each subsequent line by a small amount relative to the previous one. And to avoid the resulting model overly wrapping around on itself, I made every alternate rotation go in the reverse direction. And that is essentially what you will see when you run the program.
If you examine the output closely, you’ll see that the model comprises a long chain of lines connected at ‘hinges’, each rotated a little bit more than the previous one, and with each subsequent line alternating between using a clockwise or counterclockwise direction for rotation.
To make things even more interesting, I chose to animate the result by placing the model in a loop, in which the rotation amount slowly changes over time. The reason for this is that one particular degree of rotation might show more of a pattern than another. Plus, to test my theory that there may be patterns yet undiscovered, it would be necessary to test all the possible angles of rotation anyway.
A few additional tweaks later, such as adding in a camera viewpoint that tracks the model, zooming in and out to keep as much of the animation in full frame view as possible (with a moving and zooming background too), line thickness and alpha transparency depth cues, and finally some keyboard controls, and the program was complete.
Sadly, though, it seems that the four irrational numbers I have sofar tested (π, e, the golden ratio, and the square root of 2) have not yet yielded any discernible patterns (up to 512 bits), other than amazingly complex and beautiful examples of ‘chaos’ in action.
Anyway, to see what would happen if a pattern were found, I performed a final tweak to the program that made it able to create strings of binary from repeated random substrings. The results blew my mind with the symmetry that emerged, in what I can only describe as an everchanging ‘dance’ (as you can see), that even displays 3D effects (with no 3D algorithms).
So now it looks as if, by using this technique, if there are any patterns in irrational numbers, they could well be detectable via this process, although not the first 512 bits of the ones I have tested so far. However, by adding more and more bits, patterns may emerge further down these numbers.
I have versions of the program that go up to 250,000 bits. They run quite slowly, and I haven’t seen anything noteworthy as yet. But who knows whether even further along, the numbers may exhibit interesting effects. Or maybe a pattern might be discovered if every other bit were tested, or every third, or bits were selected via a logarithmic progression, and so on. If there is a pattern anywhere, I believe this process may be the type of program that could detect it, even if it turns out necessary to start running up the bases to do so.
In the meantime, BitDancer, the program I created for this is a fascinating mathematical toy that can create a myriad of amazing effects. I hope you get a chance to play with it – and spend a few minutes examining the different types of patterns possible by pressing the keys shown.
Posted in Articles, Features, Observations
1 Comment
Try Prime Spirals for Yourself
I’ve spent the last few days refining my prime spirals software to the point that it can now display all prime numbers, or subsets such as those separated by a distance of 2, 4, or other numbers, or primes that come in groups of three, four or more, and so on. I also substantially speeded up the animation and provided a set of keyboard controls.
With this program it’s now possible to explore this whole new world (at least to me) of prime spirals in far greater depth. For instance, every type of prime grouping I have so far tested will form spiral patterns. So, for example, if you plot only groups of three primes that appear in combinations of 2 or 4 numbers from each other (separation of groups of three by a distance of 2 only appears with the group 357 – so 5711 is accepted in this case, as is 71113, and so on), you still see them form spiral arms.
This suggests that if you were to follow those spiral arms outwards, you could more closely predict where you were likely to find further such groupings. In fact, by following the spiral arm of any grouping it may be possible to substantially narrow down the set of numbers to be checked to find any particular type of prime grouping – or even simply single prime numbers.
And I have a conjecture that by drawing a spiral that includes a known prime factor of a number, there may be a way to narrow down partner prime numbers to crack encryption systems. This is an area I haven’t yet looked into, but which I think is prime for research :)
Anyway, you can play with the program by visiting the URL below, and use the following key presses to control it:
 [1][9] Display only primes at a distance of 2 times the key press from each other. For example, [1] displays twin primes, [3] displays primes separated by 6 numbers, and so on, and [0] displays all primes again.
 [Ctrl][2][5] Display only those primes that appear in clusters of 2, 3, 4 or 5 (each separated by a maximum of 4 numbers). Press [0] to display all primes again.
 [Alt][0][9] Change the animation speed from fastest to slowest.
 [Shift][0][9] Change the pixel size from smallest to largest.
 [R] Reverse the direction of animation.
 [P] Pause and restart animation. Press twice quickly while paused to step by a single frame.
Click here to run the program in a new tab/window
As an aside, I was astonished to discover that Safari (even the old PC version that hasn’t been updated for years) is blindingly fast at drawing these spirals, running many times faster than Firefox (which comes a distant second), followed by Chrome and Opera running even more slowly, and Internet Explorer limping along in the rear (well, actually I expected that…) What is Apple doing so well here? Is it using superefficient math routines? Does it access the canvas more efficiently? I’d love to know – even Safari on my Macbook Air runs faster than Chrome or Firefox on my 16GB, 64bit, i73770 PC!
Anyway, following is the source for the complete program (as it stood on June 1st 2014), so you can view it now if you are interested:
<!DOCTYPE html> <meta charset='UTF8'> <html><body> <canvas id='canvas1' width='600' height='600'></canvas> <canvas id='canvas2' width='600' height='600'></canvas> <script> // Global Objects canvas1 = document.getElementById('canvas1') // Get canvases canvas2 = document.getElementById('canvas2') context1 = canvas1.getContext('2d') // Create contexts context2 = canvas2.getContext('2d') C = 0 // Frame counter P = getprimes(1500000) // Prepopulate primes array P[] Q = [] // Array of random numbers R = 0.0002 // Spiral radius increment S = 1 // Resume direction after pause T = 1 // Direction of animation U = 0 // For tracking prime groups V = 1 // Pixel width and height W = 0 // Animation delay X = 300 // Center of spiral... Y = 300 // ...X & Y coordinates Z = 0 // For tracking prime pairs for (var f = 0, j = 0 ; j < P.length ; ++j) // Populate random array Q[] Q.push(f += Math.floor(Math.random() * 27.2)) spiral() // Start animation // Functions function spiral() // Draw the current spiral frame { canvas1.width += 0 // Clear canvas 1 canvas2.width += 0 // Clear canvas 2 var d = (Math.PI * 100000) / P[C] // Gap between plots var n = 0 // Index counter into P[] and Q[] arrays context1.font = // Provide status info context2.font = "11pt 'Times New Roman'" context1.fillText('Primes: (π × 100000) / ' + P[C] + ' =', 0, 10) context2.fillText('Random Numbers', 0, 10) context1.fillText(d, 0, 30) if (Z == 0 && U == 0) context1.fillText('All primes', 0, 50) else if (U > 0) context1.fillText('Groups of ' + U, 0, 50) else context1.fillText('Distance: ' + Z, 0, 50) for (n = 0 ; n < P.length ; ++n) // Draw both spirals { var g = P[n] * d // Distance around spiral 1... var h = P[n] * R // ...and out from the middle var i = Q[n] * d // Distance around spiral 2... var j = Q[n] * R // ...and out from the middle var f = false // True if a point is to be plotted if (Z == 0 && U == 0) f = true // All primes else if (U > 0) // Groups of primes { f = true // Assume plot is required for (var k = 0 ; k < U ; ++k) if (P[n  k]  P[(n  k)  1] > 4) f = false // Group not found  so no plot } else if (P[n]  P[n1] == Z) f = true // Pairs of primes if (f) context1.fillRect(X + Math.floor(Math.sin(g) * h), Y + Math.floor(Math.cos(g) * h), V, V) context2.fillRect(X + Math.floor(Math.sin(i) * j), Y + Math.floor(Math.cos(i) * j), 1, 1) } C += T // Increment/decrement index into arrays if (C < P.length && C > 1) setTimeout(spiral, 4 + W * 333) // Finished, so start next frame if (C < 1) T = 1 // reverse animation direction if needed else if (C >= P.length) T = 1 } function getprimes(a) // Return array of primes up to number a { var p = [], n = 0 while (n < a) if (isprime(++n)) p.push(n) return p } function isprime(n) // Check a number for primality { for (var i = 2 ; i <= Math.sqrt(n) ; i += 1) if (n % i == 0) return false return true } document.addEventListener('keydown', function(e) // Listen to keyboard { var f = false e = e  window.event var keyChar = String.fromCharCode(e.keyCode).toLowerCase() if (e.ctrlKey) { switch(keyChar) // Select primes by group { case '1': f = true; U = 0; Z = 0; break // All primes case '2': f = true; U = 0; Z = 2; break // Distance: 2 case '3': f = true; U = 3; Z = 0; break // Groups of 3 case '4': f = true; U = 4; Z = 0; break // Groups of 4 case '5': f = true; U = 5; Z = 0; break // Groups of 5 case '0': case '6': case '7': case '8': case '9': f = true } if (f) return canceldefault(e) } if (e.altKey) { switch(keyChar) // Select Speed of Animation { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': f = true; W = parseInt(keyChar); break } if (f) return canceldefault(e) } if (e.shiftKey) { switch(keyChar) // Select pixel size { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': f = true; V = parseInt(keyChar) + 1; break } if (f) return canceldefault(e) } switch(keyChar) // Select prime pairs { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': f = true; Z = parseInt(keyChar) * 2; U = 0; break case 'r': f = true; T = T; break // Reverse direction case 'p': f = true // Pause and restart if (T != 0) { S = T; T = 0 } else { T = S } } if (f) return canceldefault(e) }) function canceldefault(e) { if (e.stopPropagation) e.stopPropagation() if (e.preventDefault) e.preventDefault() return e.returnValue = !(e.cancelBubble = true) } </script></body></html>
Posted in Articles, Features, Observations
Leave a comment
A First Hypothesis on My “Nixon” Prime Spirals
Somewhere around 200BC a Greek mathematician called Eratosthenes described a sieve method that could be used to generate prime numbers. For low prime numbers it’s not too hard to tell whether a number is prime by testing it for having integer factors. But as you move on to large and larger numbers this takes more and more time, so methods based on this sieve are often used to gain speed. It works like this:
Write down all the numbers you want to test for primality. Once you have this list locate the first prime number after 1 and erase every multiple of it. This will remove 4, 6, 8, and all other even numbers, leaving 2. Having done this locate the next unerased number, which will be 5. So now count along your list and erase every multiple of it such as 10, 15, 20, and so on. Now move onto the next number, which will be 7, and delete all multiples of that (14, 21, 28, and so on), and the next unerased number will be 11.
You see what’s happening here? One by one we are discovering the prime numbers as we move up the number list. And at the same time, we’re are quickly removing rafts of nonprime numbers throughout the rest of the list, consequently discovering primes without a single division operation in sight.
Now, imagine that you write this list of numbers in a spiral and then draw lines instead of erasing numbers when you conduct each sieve operation. Depending on how closely together you wrote the numbers, you’ll see spirals radiating out in a variety of different curves.
Considering the prime spirals I’ve been creating recently, in which only prime numbers (or pairs, triplets or other combinations of primes) are plotted, you can imagine the primes not plotted as being drawn using the sieve process in white lines. And this is what I hypothesize I am finding. These spirals actually bring out the sieve spirals, resulting in the patterns found.
Of course, when the correct spacing values are used the spirals form straight radial lines, and that’s why the images in my previous article look more like bicycle wheels than spirals – I used multiples of 360 in the distance to straighten them up. So, to remove this straightening effect I removed the 360 and replaced it with prime numbers and found spirals going in both clockwise and counterclockwise directions (at the same time), and with different curvatures too.
To get a better understanding of what is happening I then wrote the code to animate all distances between potential plot points from pπ to π ÷ 2, π ÷ 3, π ÷ 5, π ÷ 7, and so on (diving pi only by prime numbers to remove the possibility of integer divisors creating artificial patterns). What happens when π is used is you get a straight line because the distance between all potential plots is a semicircle, so the spiral is a single line going straight out. as you increase the divisor, more ‘spokes’ appear as more potential plot locations become available, until you get into divisors of a few hundred, when the spokes are so close to each other patterns can start to be revealed.
Interestingly, if this process continues, the final result will be a single straight line again. But only when it reaches π/infinity. So in the programs below, once the divisor gets into the several thousands, you’ll see a new spiral begin to emerge and the prime patterns will be harder to see, This is because the distance between potential plots is so close that plot points are overlapping each other, resulting in just a spiral line (the one that will end up straight at infinity).
So following is what happens when you use (for example), the prime number 2143 as the divisor for calculating the plotting distance gap:
Here we see another benefit to not making the ‘spokes’ straight, because now it’s possible to determine the directions in which they curve. Anyway, for comparison (and to try to check that all this isn’t hogwash and caused by simple interference patterns or something), here’s the same value used but with random numbers ending in 1, 3, 7, or 9 being plotted, rather than prime numbers – not much to see here (thankfully!):
Here is a combined program you can try for yourself to create prime and random ‘Nixon’ Spiral animations. Note that things are a little boring for the first few dozen frames, but bear with the animations, as patterns very soon start to emerge – there are also a number of keyboard options available for controlling the animation:
 Prime Spiral Animation (This is the main program)
By the way, after viewing these animations over and over, I’m now fairly sure that above a rough value of around 1700 or thereabouts, the interference effects (unexpected white ‘spokes’) of nonprime plot distance gaps is vastly reduced. So here’s a version of the Prime Spiral Animation program that counts in linearly decreasing gap sizes, starting with π ÷ 1700 (then π ÷ 1701, π ÷ 1702, and so on), rather than by the next smallest prime number fraction of π ÷ n. When you watch this animation you can see leftswirling spirals turn into radial spokes in the following frame, and then rightswirling spirals in the next. Just like turning a radio dial, I think sieves gets tuned in one (or many) at a time until they show as straight spokes at maximum ‘tuning’ (and often many different sieves can be be seen in action at the same time in a frame):
 Prime Spiral Animation 2 (nonprime plot distance steps)
Here’s an example frame from this program exhibiting these spokes (the frames immediately prior and after this display as spiral arms):
So, what do you think? Is it the Sieve of Eratosthenes we’re seeing here. And, if so, does it have implications for understanding more about prime numbers, or even finding them more easily, for example?
Posted in Articles, Features, Observations
2 Comments
Is it just me, or have I stumbled across something new about prime numbers?
There’s a thing in mathematics known as the Ulam Spiral, which is created by writing all the numbers from 1 upwards in a rotating pattern around a grid. This spiral was discovered by Stanislaw Ulam in 1963 while doodling during the presentation of a ”long and very boring paper”. What’s interesting about the Ulam spiral is that when you circle all the prime numbers, many of them surprisingly align along diagonal lines.
You can try it for yourself if you have enough time and some paper and a pencil, or even enter the numbers into a spreadsheet. Just follow the procedure on the right, and then circle, underline, cross out, or otherwise highlight all the prime numbers. I considered doing the same when I was first intrigued by the Ulam spiral but, being a programmer, decided to take things further by writing a program to map all the prime numbers onto an HTML5 canvas element.
At the same time I decided to write the spiral in such a way that as well as following a gridlike form, the distances between the numbers could be changed and the spiral allowed to grow in arcs (not straight lines). I also chose to allow the spacing between arms of the spiral to be variable so that the resulting spiral could be formatted in a wide range of different ways. For example, a grid pattern supports only 8 potential directions for straight lines to appear (N, NE, E, SE, S, SW, W, and NW), but by allowing variable distances, fewer or more directions become available. So here (with apologies if you don’t program) is a JavaScript program to do just as I described:
<!DOCTYPE html> <html> <head> <title>Prime Spirals  By Robin Nixon</title> </head> <body> <canvas id='canvas' width='900' height='900'></canvas> <script> canvas = document.getElementById('canvas') context = canvas.getContext('2d') w = canvas.width h = canvas.height x = w / 2 // Center of spiral... y = h / 2 // ...X & Y coordinates r = 0.0002 // Spiral radius increment d = Math.PI / (360 * 7) // Gap between potential plots n = 1 // Numbers being plotted loop: while (n < 2200000) { n += 1 for (i = 2 ; i <= Math.sqrt(n) ; i += 1) if (n % i == 0) continue loop context.fillRect(x + Math.sin(n * d) * r * n, y + Math.cos(n * d) * r * n, 1, 1) } </script> </body> </html>
In this program, the canvas width and height are set to 900 pixels then the variables x and y are set to point to the center of the canvas. After that r is given a value of 0.0002. This is the outward movement in pixels of the spiral. For every degree around the spiral it will move outward by that amount.
The variable d was then initially set to a value of π ÷ 360, so that each new plot point on the spiral would be at intervals of one degree. However, on the outer edges of the spiral this made the gaps very wide indeed so I changed this distance to a 7th of a degree to get much more compact results by choosing a division factor of 360 × 7. Both r and d are the values that can be changed to play with different types of spiral if you wish to run this code yourself. The last value initialized is n, which is the equivalent of the numbers counting upwards around the spiral, and will be continually incremented and checked for primality each time.
Finally there is a loop with a label of loop. It counts up to 2.2 million, locating all prime numbers up to that value by using a for loop to check for any factors. If a factor is found then n is not prime and so the continue statement resumes execution at the start of the loop, where n is incremented and then again checked for primality.
If n passes the factoring tests then the canvas is drawn on with a call to fillRect(), using x and y as the base polar coordinates, with n (the prime number) multiplied by d (the distance on the spiral between each number) and then passed through functions to obtain the sine and cosine of these values to assign as coordinates, which are then multiplied by both r (the distance between spiral arms) and n (the prime number), to finalize their positions in the spiral.
When you run this program, the result you get will be similar to the image on the left. At first glance you may not think much of it, but look closely and notice how there is an amazingly consistent repeating pattern of radial lines all the way around this image. Some places there are gaps of white, and in others there are distinct lines. What’s more when you study the lines close up you can see that they are created with primes all falling near each other, creating a line wider than one pixel, as if they are drawn towards that ‘spoke’ of the spiral.
Now, I know what many of you will be thinking, because this looks like the kind of result you might get from interference of one kind or another, such as imprecise floating point arithmetic – I also thought the same. So I modified the program to use random numbers instead of primes. As you will know, almost all prime numbers end with the digits 1, 3, 7, or 9. The only one to end with 5 is 5 itself, and we can similarly discount the number 2. So, I swapped out the code to check for factors with some to increment n (which starts off with a value of 1) by random even amounts of between 2 and 20 (to get another odd number). Then, if the resulting number doesn’t end with 5, it is plotted on the spiral. Here’s the code:
<!DOCTYPE html> <html> <head> <title>Random Spirals  By Robin Nixon</title> </head> <body> <canvas id='canvas' width='900' height='900'></canvas> <script> canvas = document.getElementById('canvas') context = canvas.getContext('2d') w = canvas.width h = canvas.height x = w / 2 // Center of spiral... y = h / 2 // ...X & Y coordinates r = 0.0002 // Spiral radius increment d = Math.PI / (360 * 7) // Gap between potential plots n = 1 // Numbers being plotted while (n < 2200000) { n += Math.floor(Math.random() * 10) * 2 if (n % 5 != 0) context.fillRect(x + Math.sin(n * d) * r * n, y + Math.cos(n * d) * r * n, 1, 1) } </script> </body> </html>
So, very little has changed here, other than that there will now be a combination of primes and nonprimes plotted on the spiral. So what does the output look like? Well, as you can see from the image on the right, it’s pretty much as you’d expect, a smooth and randomlooking image, with only marginal demonstration of radial lines, caused only by the fact that the distance between plot locations is one 7th of a degree. The smaller this value is made, the less obvious these lines become.
If you try, as I earlier suggested, modifying the values of r and d with either of these programs, you will see very little difference in the output from the latter one, but a wide variety of different sets of radial lines from the former, indicating, as far as I can tell, that there is a lot more order and repetition in prime numbers than we may have hitherto realized.
I have Googled for prime spirals and searched for similar images to those I have been getting and not come across any as yet, so maybe this is something new to add to the Ulam Spiral. At least, it looks that way to me and I would welcome input from any mathematicians on the subject. Even if it’s not new, it’s still new to me, and lots of fun to play with, and I hope you’ll find it the same.
I have uploaded both examples to my website where you can try them for yourself. If you’re curious I do recommend you download them and try playing with the code to see what else you can discover:
Update: My latest work in progress which includes both prime and random animations, with a number of keyboard options for fine control is now here:
Have fun, and please let me know what you think.
Note: It has been suggested to me that 360 has multiple divisors and therefore using this value will cause erroneous results. However, 360 × 7 is 2520, and when I swap that out for primes such as 2503, 2521, or other primes sufficiently large to not leave too wide a gap between ‘spokes’, I still frequently see these radial lines, although they often show up as spiral lines. And, again, comparing with the random version of the program, I have been so far unable to replicate these radial lines in a similar fashion with any combination of different values. So I’m still scratching my head…
And there’s more!
I’ve been playing around a lot more with this idea and decided to pick out subsets of prime numbers such as only those that are two numbers away from each other (also known as twin primes), or primes that come in groups of two or more separated by either two or four numbers between each, and so on. And the result of this has further amazed me.
So let me show you what kind of spirals you get when you do this, starting off with the spiral of all primes for comparison.
Spiral of all primes:
Spiral of twin primes:
Spiral of triplet primes:
Spiral of primes separated by 4 numbers:
Spiral of primes separated by 6 numbers:
Spiral of primes separated by 12 numbers:
(And for comparison) Spiral of random odd numbers not ending in 5:
In all these prime number cases only the final prime in a group is plotted. What is amazing to me is that nomatter which way you try to make it unlikely that the prime number sequence you select will reveal a pattern, there is always a pattern somewhere – even when you only plot groups of three primes near each other, or primes separated by the value 12. If these radial line patterns were an anomaly I don’t think they would interact so directly with the prime sequences selected.
I mean, look at the spiral for primes separated by 6 numbers. This isn’t every 6th number that’s a prime or something as semiordered as that. It shows only those primes that have a separation of 6 numbers between them (and only the latter of each pair, so that no subpattern can form) – and a distinct pattern is generated from it. I’m dieing to be put out of my misery and be proved wrong on this – but it does seem like we are seeing something new here at the moment.
Here are the new files to create these spirals:
PS: I tried plotting the Mersenne Primes but there are too few of them to tell whether there’s a pattern evolving. I’ll see if I can plot some other types of prime, though.
Posted in Articles, Features, Observations
7 Comments
The Everything Numbers
Every word ever written or spoken, every thought ever conceived, every book or poem ever crafted, every movie ever filmed or program developed, every strand of DNA, every atomic structure, every gas nebula, every black hole – in the past, now, or in the future – has existed since the dawn of time, and probably even longer!
You’re probably aware that the value of π (the ratio of a circle’s circumference to its diameter) is infinite because it is what is known as irrational (in that cannot be expressed exactly as a common fraction), and never settles into a repeating pattern – which means that every possible sequence of digits appears somewhere in the number. And if you represent π in binary, the sequence of 1 and 0 bits has the same property. Therefore every item of digital content (whether books, programs, videos, music, or whatever) can be found somewhere in this number.
However, because it isn’t intuitive (and takes some fairly complex mathematics to prove that π is infinite), you might be tempted to dismiss this thought as merely somewhat interesting – if, that is, it really happens to be true. So let’s look at a similar irrational number that is easily demonstrated to be infinite by constructing it ourselves. Take the binary value for 1, and place after it the binary value for 2. Then follow this with the binary for 3, 4, 5 and so on until infinity, and you will end up with a number that begins 1 10 11 100 101. With spaces removed (and a few more bits added) it starts to look like this:
11011100101110111100010011010101111001101111110000…
If you continue this process to a significant length and then analyze the binary digits, you can determine that every possible combination of digits will eventually appear somewhere in this number. Although it could be trillions of light years along a printed version of the number, it will be there somewhere.
Now that we have a number we can intuitively understand must contain every possible sequence of 1 and 0 bits, let’s try and get our heads around what this means (if anything). Referring back to my first paragraph, everything (and I mean everything) must be in this number. Every different arrangement of anything within this universe that ever has been or will be is represented somewhere inside.
And all you need to do to reference it, is point to the start of a sequence, and possibly make a note of its length – although in the case of media it’s pretty obvious when you have reached the end, because there’s usually some text or visuals to tell you. So on the whole you can get away with just two numbers to reference almost anything. You need an irrational number, and a second number to act as an index into that number – that’s it!
This article you are reading now, indeed all my articles, and every book I have ever written (every one of them) is somewhere in that number, and it always has been. So I have to ask myself, why on earth do I put all the time into writing these things, when they already exist within the very fabric of mathematics – and therefore the universe itself?
And what about free will? Every thought and every decision I have ever made can be represented in language, and therefore in binary, and so they are all in there too. And so are all the thoughts and decisions I will ever make in the future. All set in stone (so to speak) at the big bang. Or, if mathematics existed in some form previously, perhaps long (or infinitely) before the big bang.
And yet, I can still choose to write this article – at least, it feels like a choice. But is it? And what about multiplicity. If one of my books is in the number once, it’s in there an infinite number of times! And the near misses? This article is not only in that number an infinite number of times, an infinite number of variations (with slightly different sentence structures, and different word orders) are also in there too! A bazzillion of close matches to accompany the infinity of direct copies.
And, of course, all these things are in every other similar number such as π, e, the square root of 2, and the golden ratio. In fact, there is in infinite number of irrational numbers so, not only is everything that ever is, was, or will be, represented an infinite number of times in one irrational number, these things are repeated across an infinite number of irrational numbers. And get this. Because infinity, every one of these infinite number of infinite numbers is also within every other one. They are all inside each other, multiple infinity times over.
So, not only is everything we have done, do, will do, and are, represented infinitely in a few interesting numbers – these things are infinitely repeated across an infinite part of the mathematical universe. So now, all I need to do is write a program to find my books and articles in these numbers for me, and I can retire to live the good life…
Or, if I can get lucky and find the program to do that in there, I won’t even have to write it!
Posted in Articles, Observations
Leave a comment
Jamie: The JavaScript Monitor and Editor
I’m moving into more interesting areas of publishing, including a totally new type of eBook (that won’t simply be an electronic version of a paperback, but with multimedia added :) As part of this I’ve been developing a new way of teaching JavaScript programming for my videos: The Jamie JavaScript Monitor and Editor.
I wanted a simple and clean environment that could be totally separated from a web document, and which would also keep track of all variables and objects, so that learning programmers would have an ataglance view of the state of the example programs supplied with my books (and now videos).
I also wanted an easy way for them to share scripts with each other (and with me) that didn’t require storing masses of data on a central web server (ideally with scripts passed in a query string). More than that, since so much JavaScript programming is timerdriven, I needed a way to peek into intervals and timeouts, report on any errors, and keep track of the variables used in them (and also turn them off for runaway scripts).
At the same time I wanted as helpful error reporting as possible, an expression evaluator for quickly testing things, and an output window where results could be displayed, as well as in the main browser.
And so the result is the Jamie JavaScript Monitor / Editor. Initially written for me and my programming students, now that it’s finished (at least, as finished as any programming project can be) I think it has turned out quite well, so I’ve made the whole thing public and put it on the goj.me domain to make accessing it easy to remember  Go Jamie!
I’ll be using Jamie extensively in my forthcoming books and courses, and hope you will find it useful too!
Posted in News
Leave a comment
Lower your blood pressure quickly, cheaply and safely
As a consequence of the low carbohydrate / high fat diet I have been eating since July this year my blood pressure has been slowly declining, and I have been monitoring it closely so that I can get my doctor to adjust my hypertension medications as necessary, as you can see from the chart on the left for October.
But check out what comes after the dotted line!
Please follow this link to my new website, Fully Grounded, to discover what I did to quickly and dramatically further reduce my blood pressure after that point.
Posted in News
Leave a comment