I have implementted a simple JavaScript function to find the list of abundant numbers and print them on the screen.
an abundant number is a number for which the sum of its proper divisors is greater than the number
The function printAbundantNumbers()
, takes an argument, which is a range that tells the function how many abundant numbers that it should find and print out on the screen. The function also includes several smaller functions to ensure the readability of the code - so that each functionality will be performed with no conflicts to the other code.
I think the code is quite long. Is there a way to shorten it?
Here is the code:
function printAbundantNumbers(num) {
const concatAbundantNumbers = function(){
const finalArray = collectAbundantNumbers().map(arr=>arr[1]*arr[arr.length-1]);
return finalArray; // Return the final array.
}
// Collects all abundant numbers.
const collectAbundantNumbers = function (){
let listOfFactors = collectFactorsForEachNumbers(num).filter(e=>addArray(e)>(e[1]*e[e.length-1])); // Find all the factors and loop through them. If the sum of these factors is greater than the number, then assign them to a variable.
return listOfFactors;
}
// Collect factors for each number.
const collectFactorsForEachNumbers = function (num){
let listOfIndividualElementFactors = [];
for(let i=2;i<=num;i++) {
let factors = findFactor(i); // find factors.
listOfIndividualElementFactors.push([...factors]); // Making a 2-d array out of this and assign to the variable.
}
return listOfIndividualElementFactors;
}
// find factors.
const findFactor = function (num){
let listOfFactors = [];
for(let i=1; i<num;i++) {
if(num%i===0)listOfFactors.push(i);
}
return listOfFactors;
}
// add arrays
const addArray = function(arr){
let sum=0;
arr.forEach(e=>sum+=e); // loop through the array and them.
return sum;
}
concatAbundantNumbers().forEach(e=>console.log(e+"\n")); // writes the abundant to the screen.
}
printAbundantNumbers(200);