[Vue.js] Online Goldbach's Conjecture Demo


Goldbach's conjecture - Every even integer greater than 2 can be written as the sum of two primes. Given a positive even integer, this online demo returns the two primes. The UI interaction is written using Vue.js, and the algorithm is implemented using JavaScript.

{{ result }}

HTML:

<div id="vueapp">
  <input v-model="intn" placeholder="Input even integer > 2">
  <p>{{ result }}</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

Given an input from user, we check if the input is an integer, if the input is greater than 2, and if the input is even. Then we use Sieve of Eratosthenes to find out all primes up to the user input integer, and find that the two primes that sum of which is user input integer.

JavaScript:

'use strict';

function SieveOfEratosthenes(n) {
      // Create a boolean array "prime[0..n]" and initialize
      // all entries it as true. A value in prime[i] will
      // finally be false if i is Not a prime, else true.
      var integers = [];
      for (var i = 2; i < n+1; i++) {
              integers[i] = true;
      }

      for (var p = 2; p*p <= n; p++) {
              // If integers[p] is not changed, then it is a prime
              if (integers[p] == true) {
                      // Update all multiples of p
                      for (var i = p * 2; i <= n; i += p) {
                              integers[i] = false;
                      }
              }
      }

      // return all prime numbers <= n
      var primes = [];
      for (var p = 2; p <= n; p++) {
              if (integers[p] == true) {
                      primes.push(p);
              }
      }

      return primes;
}

function Goldbach(n) {
  var primes = SieveOfEratosthenes(n);
  for (var i=0; i < primes.length; i++) {
    var p1 = primes[i];
    var p2 = n - p1;
    if (primes.indexOf(p2) != -1) {
      return [p1, p2];
    }
  }
}

new Vue({
  el: '#vueapp',
  data: {
    intn: 4,
    result: ""
  },
  watch: {
    intn: {
      immediate: true,
      handler(val, oldVal) {
        var n = parseInt(val);
        if (isNaN(n)) {
          this.result = "please input integer";
          return;
        }
        if (n < 3) {
          this.result = "input integer must > 2";
          return;
        }
        if (n%2 == 1) {
          this.result = "input integer must be even";
          return;
        }
        var pp = Goldbach(n);
        this.result = (val + " = " + pp[0] + " + " + pp[1]);
      }
    }
  }
});

Tested on:

  • Chromium 65.0.3325.181 on Ubuntu 17.10 (64-bit)
  • Vue.js 2.5.16

References:

[1][JavaScript] Sieve of Eratosthenes
[2][Golang] Goldbach's conjecture
[3][Vue.js] Input Text Element Change Event
[4][JavaScript] Check if Value of Input Text Field is Integer
[5]Watchers not triggered on initialization - Get Help - Vue Forum