Finding two numbers given their sum and Highest Common Factor using JavaScript


Problem

We are required to write a JavaScript function that takes in two numbers. The first number represents the sum of two numbers and second represents their HCF (GCD or Greatest Common Divisor).

Our function should find and return those two numbers.

Example

Following is the code −

 Live Demo

const sum = 12;
const gcd = 4;
const findNumbers = (sum, gcd) => {
   const res = [];
   if (sum % gcd !== 0){
      return -1;
   }else{
      res.push(gcd);
      res.push(sum - gcd);
      return res;
   };
};
console.log(findNumbers(sum, gcd));

Output

[4, 8]

Updated on: 20-Apr-2021

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements