JSFiddle - React, Tailwind, and code Playground
by Andrew Poes
HTML
<!-- Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000. -->
CSS
.print {
position: relative;
display: inline-block;
background-color: black;
color: white;
font-family: Helvetica, Helvetica-Neue, sans-serif;
font-weight: bold;
font-size: 24px;
letter-spacing: -1.5px;
padding: 4px 8px;
}
body {
background-color: #eeeeee;
}
}
input {
padding: 20px;
}
}
JavaScript
$(document).ready(function() {
var cache = {};
var pairs = []
for (var i = 0; i < 10000; ++i) {
var s = getFactorsForNum(i, cache);
var p = getFactorsForNum(s, cache);
if (i != s && i == p) {
if (pairs.indexOf(i) == -1) {
pairs.push(i);
}
if (pairs.indexOf(s) == -1) {
pairs.push(s);
}
}
}
print(pairs);
var s = sum.apply(null, pairs);
print(s);
})
function sum() {
var s = 0;
for (var i = 0; i < arguments.length; ++i) {
s += arguments[i];
}
return s;
}
function getFactorsForNum(num, cache) {
if (num in cache) {
var s = cache[num]
return s;
} else {
var f = factors(num);
var s = sum.apply(null, f);
cache[num] = s;
return s;
}
}
function factors(num) {
var limit = Math.sqrt(num) << 0
if (limit == 1) {
if (num > 1) {
return [1];
}
else {
return [0];
}
}
var factors = [];
for (var i = 1; i <= limit; ++i) {
var d = num / i;
if (d%1 == 0) {
factors.push(i);
if (d != num) {
factors.push(d);
}
}
}
return factors.sort(function(a, b){return a-b});
}
function sum() {
var s = 0;
for (var i = 0; i < arguments.length; ++i) {
s += arguments[i];
}
return s;
}
function print() {
var args = Array.prototype.slice.apply(arguments)
var str = ""
for (arg of args) {
str += arg + ", "
}
str = str.substring(0, str.length - 2)
var el = newel(str)
$("body").append(el)
$("body").append("</br>")
}
function newel(str) {
var el = document.createElement("div")
$(el).html(str)
$(el).addClass("print")
return el
}