Online Prime Factorization


positive integer:

{{ primes }}

Online prime factorization tool. The algorithm comes from GeeksforGeeks [1] and implemented in JavaScript. The UI is implemented using Vue.js. The following is complete source code.

HTML:

<div id="vueapp">
  positive integer: <input v-model="intn" placeholder="Input positive integer">
  <p>{{ primes }}</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. Then we run the sieve algorithm to check if the number is prime.

JavaScript:

'use strict';

// Get all prime factors of a given number n
function PrimeFactors(n) {
  if (n==1) {return [1];}

  var pfs = [];
  // Get the number of 2s that divide n
  while (n%2 == 0) {
    pfs.push(2);
    n /= 2;
  }

  // n must be odd at this point. so we can skip one element
  // (note i = i + 2)
  for (var i=3; i*i <= n; i += 2) {
    // while i divides n, append i and divide n
    while (n%i == 0) {
      pfs.push(i);
      n /= i;
    }
  }

  // This condition is to handle the case when n is a prime number
  // greater than 2
  if ( n>2 ) {
    pfs.push(n);
  }

  return pfs;
}

new Vue({
  el: '#vueapp',
  data: {
    intn: 6,
    primes: ""
  },
  watch: {
    intn: {
      immediate: true,
      handler(val, oldVal) {
        var n = parseInt(val);
        if (isNaN(n) || n<1) {
          this.primes = "please input positive integer";
          return;
        }

        this.primes = PrimeFactors(n);
      }
    }
  }
});

Tested on:

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

References:

[1]Efficient program to print all prime factors of a given number - GeeksforGeeks
[2][Golang] Get All Prime Factors of Integer Number
[3][Vue.js] Online Sieve of Eratosthenes Demo