- 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
Integers have sum of squared divisors as perfect square in JavaScript
Problem
We are required to write a JavaScript function that takes in a range specified by an array of two numbers m and n.
Our function is supposed to find all integers between m and n (m and n integers such as 1 <= m <= n) such that the sum of their squared divisors is itself a square.
It should return an array of subarrays. The subarrays will have two elements: first the number the squared divisors of which is a square and then the sum of the squared divisors.
Example
Following is the code −
const range = [1, 500]; const listSquared = ([m, n]) => { const res = []; for (let i = m; i <= n; ++i) { let sum = getDivisors(i).reduce((sum, n) => sum + n * n, 0); let ok = Number.isInteger(Math.sqrt(sum)); if (ok) { res.push([i, sum]); } } return res; } function getDivisors (n) { const divisors = []; for (let i = 1; i <= n / 2; ++i) { if (n % i) { continue; } divisors.push(i); } return divisors.concat([n]); } console.log(listSquared(range));
Output
[ [ 1, 1 ], [ 42, 2500 ], [ 246, 84100 ], [ 287, 84100 ] ]
Advertisements