Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Factors of a number

/*
	JavaScript program for factors of a number by lolman_ks.
    Same logic can be used to build this program in other languages.
*/
/*
	Logic: Divide the number by every number less than half of the number and 
    check for exact divisibility.
    Add to the factors array if exactly divisible.
*/

function factors(number){
  	var factor_array = []; //Create an empty array. 
  	//Run a loop to check divisibility.
	for(let i = 0;i < Math.ceil(number / 2);++i){
    	if(number % i == 0) factor_array.push(i); //Check for exact divisibility.
    }
 	factor_array.push(number); //Add the number itself in the factor array.
  	return factor_array;
}

//Program for perfect number can also be built using the above function.

function perfect_number(number){
	const factor_array = factors(number);
  	var sum = 0;
  	for(let i = 0;i < factor_array.length;++i){
    	sum += factor_array[i];
    }  
  	if(sum == number * 2) return true;
  	else return false;
}

/*
	I hope that my answers are useful to you. Please promote them if they are.
    #lolman_ks.
*/
 
PREVIOUS NEXT
Tagged: #Factors #number
ADD COMMENT
Topic
Name
7+8 =