
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Two Numbers that Equal the Sum of the Rest in JavaScript
Suppose following is the problem:
We have a sequence of numbers starting from 1 and upto any arbitrary number, let's call it num. We have to pick two such numbers from the sequence (let's call them m and n), such that:
sum(1 to num) - (m + n) = m * n
And finally, we should return an array of groups of all such numbers.
For example −
If the input is −
const num = 10;
Then the output should be −
const output = [ [7, 6] ];
because sum(1 to 10) = 55
and,
55 - (6 + 7) = 6 * 7 = 42
Example
The code for this will be −
const num = 10; const pickNumbers = num => { const sum = (num) * (num + 1) * (.5); const results = []; for (let n = 1; n <= num; n++) { let first = sum - n; let second = n + 1; if (first % second === 0) { let m = first / second; if (m < num && m !== n && results.every(group => group[0] + group[1] !== m + n)){ results.push([m, n]); } } } return results; } console.log(pickNumbers(10));
Output
And the output in the console will be −
[ [7, 6] ]
Advertisements