![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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 all solutions of a Diophantine equation using JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should find all such number x and y such that −
x^2 - 4y^2 = n.
And it should return an array of all such pairs.
Example
Following is the code −
const num = 90005; const findSolution = (num = 1) => { const res = []; let a, b; for(let a = 1; a <= Math.sqrt(num); a++){ if(Number.isInteger(b = num/a)){ if(Number.isInteger(x = (b+a)/2)){ if(Number.isInteger(y = (b-a)/4)){ res.push([x, y]); }; }; }; }; return res; }; console.log(findSolution(num));
Output
[ [ 45003, 22501 ], [ 9003, 4499 ], [ 981, 467 ], [ 309, 37 ] ]
Advertisements