I have an assignment that requires me to find if the sum of the factors of a number minus the number itself is equal to the number. I have written the function below but does not return the correct factors. Please help!
function findNumbers(numbers){
let factorNumbers = [];
for(i = 1; i < numbers; i ){
if(numbers % i === 0){
return factorNumbers.push(i);
}
};
}
CodePudding user response:
You just pushed the factors in an array. Firstly, you have to add them up and also call the function and console log the result or maybe write an if statement to verify whether this number is a perfect number or not.
function findNumbers(number)
{
let result = 0;
for(let i=1; i<=number/2; i )
{
if(number%i === 0)
{
result = i;
}
}
console.log(result);
}
findNumbers(6);
CodePudding user response:
You need to check each number up to and equaling the number you pass in to the function, and then return the array after the iteration is complete.
function findFactors(number) {
const factorNumbers = [];
for (let i = 1; i <= number; i ) {
if (number % i === 0) {
factorNumbers.push(i);
}
}
return factorNumbers;
}
console.log(findFactors(12));
console.log(findFactors(30));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>