jQuery method for finding perfect Numbers up to n

  • 2020-06-22 23:45:05
  • OfStack

This article illustrates how jQuery finds perfect Numbers up to n. Share to everybody for everybody reference. The specific analysis is as follows:

The completeness of a number depends on its divisors.

For example, the factors of 12 are 1,2,3,4 and 6. When the sum of the factors of a number is greater than the number itself, the number is said to be "surplus". So 12 is an int, because the factors add up to 16. On the other hand, when the sum of the factors of a number is less than the number itself, the number is said to be deficient. So 10 is a deficit, because its factors (1, 2, and 5) add up to only 8.

The most meaningful and rarest Numbers are those whose sum of their factors is exactly equal to themselves, and they are perfect Numbers.

-- Fermat's Great Theorem

To find the perfect number, we first need to calculate the factor of the number, baidu review 1 under what is the factor.

Factor: If the integer n is divided by m and the result is a remainder integer, then m is a factor of n. It is important to note that this relationship holds only if the dividend, divisor, and quotient are integers and the remainder is zero. Conversely, we call n a multiple of m.


<!DOCTYPE html> 
<html> 
<head> 
 <meta charset="utf-8"> 
 <title>JS Bin</title> 
</head> 
<body> 
 <input type="text" id="num"/> 
 <button id="calc"> To calculate </button> 
 <p id="result"></p> 
</body> 
</html> 


/* 
 *  Looking for n The perfect number within  
 */ 
function $(id){ 
 return document.getElementById(id); 
} 
// Determine if it is a positive integer  
function isIntNum(number){ 
 var num = number; 
 if((!isNaN(num)) && (parseInt(num) == parseFloat(num))){ 
  return true; 
 }else{ 
  return false; 
 } 
} 
$("calc").addEventListener("click",function(){ 
 var inputNum = $("num").value, 
   $result = $("result"), 
   factorArr = [], 
   resultArr = [], 
   i = 0, 
   j = 0, 
   sum = 0; 
 // Verify that the input is a positive integer  
 if(isIntNum(inputNum)){ 
  console.log("right"); 
 }else{ 
  $result.innerHTML = " Error: Please enter a positive integer "; 
  return false; 
 } 
 // Go through all the Numbers  
 for(var k = 1;k < inputNum;k++){ 
  // Reset the variable for each calculation  
  factorArr.length = 0; 
  sum = 0; 
  // Find the factor of the current number  
  for(i = 1;i < Math.floor(k/2)+1; i++){ 
   if(k % i === 0){ 
    factorArr.push(i); 
   } 
  } 
  // Sum of factors  
  for(var m = 0;m < factorArr.length;m++){ 
   sum += factorArr[m]; 
  } 
  // If the factor sum is equal to the current number, the perfect number criterion is met  
  if(sum === k){ 
   resultArr.push(k); 
  } 
 } 
 $result.innerHTML=resultArr; 
});

Hopefully this article has been helpful in your jQuery programming.


Related articles: