2

Online Calculate Sum of Proper Divisors

 2 years ago
source link: http://siongui.github.io/2018/05/08/online-calculate-sum-of-proper-factors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Online Calculate Sum of Proper Divisors

May 08, 2018

positive integer:

Prime Factors: [ 2, 2, 71 ]

Sum of Proper Divisors: 220

Online tool for prime factorization and calculating sum of proper divisors. The following is source code of the tool. For more details of the algorithm, see [1].

HTML:

<div id="vueapp">
  positive integer: <input v-model="intn" placeholder="Input positive integer">
  <p>Prime Factors: {{ primes }}</p>
  <p>Sum of Proper Divisors: {{ sum }}</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

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;
}

function SumOfDivisors(pfs) {
  var m = {};
  for (var i = 0; i < pfs.length; i++) {
    var prime = pfs[i];
    if (m.hasOwnProperty(prime)) {
      m[prime] += 1;
    } else {
      m[prime] = 1;
    }
  }

  var sum = 1;
  for (var prime in m) {
    var exponents = m[prime];
    sum *= (Math.pow(prime, exponents+1)-1) / (prime-1);
  }
  return sum;
}

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

        var pfs = PrimeFactors(n);
        this.primes = pfs;
        this.sum = (SumOfDivisors(pfs) - n);
      }
    }
  }
});

Tested on:

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

References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK