IVAN SIVAK
  • About
  • Blog
  • CV
  • Contact

ReactJS & Sieve of Eratosthenes - Prime Numbers

12/27/2015

0 Comments

 
The Sieve of Eratosthenes is an ancient algorithm for finding prime numbers up to a given limit. As stated in Wikipedia.
It is quite simple but awesome. As always I like simple solutions. It is not the fastest though - runs in O(NLog(LogN)) but it's robust enough. By the way, the fastest prime numbers generator is currently the Sieve of Atkin.
So what do we in this article? We're going to create a simple page with one input that represents a given limit N and marks all prime numbers P (so that P <= N) on a sequence of numbers that is rendered using ReactJS.
Why React? Well, one of the key React's feature is the Virtual DOM. Basically, once you update the model the engine renders only what's necessary and skips the elements that have not been updated. This is very powerful feature. For those folks who haven't heard much about React I recommend following video to make a better picture.

The code

OK, let's get to coding. The algorithm itself is pretty straightforward.
Code Editor

    
When you check the project on GitHub you'll also notice the ugly initial array fill
Code Editor

    
I know I could use the Array.prototype.fill() as part of ECMAScript 6 but since this particular function is not yet supported by all browser I'm gonna stick up with old loop method.
The React's part is quite simple. We're gonna create 2 classes. One that represents the whole view elements and one that represents the dynamic array being rendered as a sequence of spans.
Code Editor

    
The key method is handleSubmit. Notice the setState function that sets the model list array to a newly created array of booleans. If you start with limit of e.g. 100 and later increase the limit to e.g. 130 you'll nicely see how the previously rendered elements are staying intact. Only newly inserted prime numbers are being signalized by color animation. That's because React knows what changed in the model list array.
The array view class is then very simple.

    

Check it out

As usual the whole project is at your disposal on plunker and also GitHub. Enjoy. By the way - a good tip for online JSX compiling service - Babeljs.io.
0 Comments



Leave a Reply.

    About

    Blog about my programming experiments, tests and so on.

    View my profile on LinkedIn

    Categories

    All
    Algorithms
    Angular 2
    ASP.NET
    ASP.NET Core
    Aurelia JS
    Cryptography
    Data Structures
    Gulp
    JavaScript
    Math
    MVC6
    .NET Core
    React JS
    Security
    SQL Server

    Archives

    November 2016
    October 2016
    September 2016
    May 2016
    March 2016
    February 2016
    January 2016
    December 2015
    October 2015

    RSS Feed

Ivan Sivak


Stack overflow

Stack overflow profile

LinkedIn

LinkedIn profile

Email

ivansivak@outlook.com

GitHub

GitHub repository
  • About
  • Blog
  • CV
  • Contact