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

JavascriptWeb DevelopmentFront End Technology

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]
raja
Published on 20-Apr-2021 09:42:28
Advertisements