
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Finding tidy numbers - JavaScript
- Finding pandigital numbers using JavaScript
- Finding two golden numbers in JavaScript
- Finding lunar sum of Numbers - JavaScript
- Finding special type of numbers - JavaScript
- Finding three desired consecutive numbers in JavaScript
- Finding Lucky Numbers in a Matrix in JavaScript
- Finding Armstrong numbers in a given range in JavaScript
- Finding desired numbers in a sorted array in JavaScript
- Finding the nth digit of natural numbers JavaScript
- Finding even length numbers from an array in JavaScript
- Finding nth digit of natural numbers sequence in JavaScript
- Finding sequential digit numbers within a range in JavaScript
- Finding value of a sequence for numbers in JavaScript
- Count numbers upto N which are both perfect square and perfect cube in C++
Advertisements