JavaScript finds the perfect number within 1000

PHPz
Release: 2023-05-21 10:53:06
Original
695 people have browsed it

What is the perfect number?

In mathematics, a perfect number is a special type of natural number. The sum of all its proper factors (that is, factors other than itself) is equal to itself.

For example: 6 is a perfect number because all the true factors of 6 are 1, 2, and 3, and their sum is exactly equal to 6.

So how to use JavaScript to find the perfect number within 1000?

We can first write a function to determine whether a number is a complete number:

function isPerfectNumber(num) {
  let sum = 0;
  for (let i = 1; i <= num / 2; i++) {
    if (num % i === 0) {
      sum += i;
    }
  }
  return sum === num;
}
Copy after login

The function of this function is to calculate the sum of the true factors of a number. If it is equal to the number itself, it returns true, otherwise false is returned.

Next, we can write a loop to enumerate every number within 1000 and determine whether it is a complete number:

for (let i = 1; i <= 1000; i++) {
  if (isPerfectNumber(i)) {
    console.log(i);
  }
}
Copy after login

The function of this loop is to enumerate every number within 1000 Number, if the number is complete, print it out.

Combine these two parts to get the complete code:

function isPerfectNumber(num) {
  let sum = 0;
  for (let i = 1; i <= num / 2; i++) {
    if (num % i === 0) {
      sum += i;
    }
  }
  return sum === num;
}

for (let i = 1; i <= 1000; i++) {
  if (isPerfectNumber(i)) {
    console.log(i);
  }
}
Copy after login

By running this code, you can output a complete number within 1000. On my machine, the output of this code is:

1
6
28
496
Copy after login

Therefore, there are 4 perfect numbers within 1000, which are 1, 6, 28 and 496.

Of course, if we need to find a larger completion number, this program may run for a long time. Because the number of perfect numbers is very limited, and as the value increases, the intervals between perfect numbers become larger and larger, so finding larger perfect numbers may require more efficient algorithms.

The above is the detailed content of JavaScript finds the perfect number within 1000. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template