Code Wars: Recreate One

In this algorithm we have to take 2 integers and in this range (ex. 1,42) we want to find the sum of squared divisors is itselfs a square like 42. The result will be an array of arrays and each subarray will have the number whose square divisors is a square and then the sum of the squared divisors.

My approach was to create a basic function(the constructors) that iterates within the rage and then to create a method that finds the sum of a squared divisor like the one below.

function sumDivisors(num) {

var sum = 0;
var arr = [];
for (var i = 1; i <= num; i++) {
if (!(num % i)) {
sum += i * i;
}
}
return sum;
}



and after on my init function i iterate through the range of the given numbers to find the sum of squared divisors that are itself a square and then print the result as an array



function listSquared(m, n) {

var arr = [];
for (var i = m; i <= n; i++) {
var ns = Math.sqrt(sumDivisors(i));
if (Number.isInteger(ns)) {
var newArr = [i, ns * ns];
arr.push(newArr);

}
}
return arr;
}



Here is the complete code:


function listSquared(m, n) {

var arr = [];
for (var i = m; i <= n; i++) {
var ns = Math.sqrt(sumDivisors(i));
if (Number.isInteger(ns)) {
var newArr = [i, ns * ns];
arr.push(newArr);

}
}
return arr;
}

function sumDivisors(num) {

var sum = 0;
var arr = [];
for (var i = 1; i <= num; i++) {
if (!(num % i)) {
sum += i * i;
}
}
return sum;
}

Σχόλια