- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding perfect numbers in JavaScript
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
For example −
28 is a perfect number, because 28 = 1 + 2 + 4 + 7 + 14
We are required to write a JavaScript function that takes in a number, say n, and determines whether or not n is a perfect number.
Example
const num = 28; const checkPerfectNumber = (num = 1) => { if(num === 1) { return false; }; let sum = 1; for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++){ if(num % i === 0) { sum = sum + i + num / i; if(sum > num) { return false; } }; }; return sum === num; }; console.log(checkPerfectNumber(num));
Output
And the output in the console will be −
true
Advertisements