Im big fan of Numberphile Youtube channel. Few days ago Brady Haran published a video abou “Primal spiral”. It was really interesting and I was thinking if I can generate such a spiral with Javascript in the browser.
Today I was forced to spend whole day in the train from Bratislava to Kosice and back (12 hours) so I was trying to do something just to keep me sane. So I tried to created generator for Ulam (prime) spiral with Javascript. The result is here.
Ulam spiral
What is Ulam spiral?
The Ulam spiral, or prime spiral (in other languages also called the Ulam Cloth) is a simple method to visualise the prime numbers. It reveals the apparent tendency of certain quadratic polynomials to generate unusually large numbers of primes. It was discovered by the mathematician Stanislaw Ulam in 1963, while he was doodling during the presentation of a “long and very boring paper” at a scientific meeting
This is a simpler explanation:
Demo app
Demo application is using HTML5 canvas for rendering the spiral and web workers to get the information if the number is prime or not.
Web workers are really useful in this scenario because the information if the number is prime number or not can be calculated in the “background”, so it doesn’t block rendering (at least it shouldn’t).
Without web workers, the browser becomes more unstable even with smaller sizes of the spiral.
You can try the demo application here:
Be careful with the parameters of the spiral. If you choose too big number for spiral size it may block your browser for few seconds (or minutes).
View source code on github.com
All code is open source and dual licensed under GPL and MIT. Feel free to use it.
If you have any question feel free to ask.
Hi, I think your bounds checking in setDirection function should be &&
if ((dirIndex >= 0 || dirIndex < 4)) {
Why do you think that?