Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding two numbers given their sum and Highest Common Factor using JavaScript
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.
Problem
Given the sum and HCF of two numbers, we need to find the original two numbers. For two numbers to have a specific HCF, both numbers must be multiples of that HCF.
Mathematical Approach
If two numbers a and b have HCF h, then:
-
a = h × mandb = h × nwheremandnare coprime - The sum becomes:
a + b = h × (m + n) - Therefore:
sum = h × (m + n)
Example
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));
[4, 8]
How It Works
The algorithm works as follows:
- Check if the sum is divisible by the GCD. If not, no solution exists.
- The simplest solution is one number equals the GCD itself.
- The second number becomes
sum - gcd. - This ensures the HCF condition is satisfied.
Complete Example with Validation
function findTwoNumbers(sum, hcf) {
// Check if solution exists
if (sum % hcf !== 0) {
return "No solution exists";
}
// Find the two numbers
const num1 = hcf;
const num2 = sum - hcf;
// Verify the HCF
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
if (gcd(num1, num2) === hcf) {
return [num1, num2];
} else {
return "Solution doesn't satisfy HCF condition";
}
}
// Test cases
console.log("Sum: 12, HCF: 4 =>", findTwoNumbers(12, 4));
console.log("Sum: 15, HCF: 5 =>", findTwoNumbers(15, 5));
console.log("Sum: 10, HCF: 3 =>", findTwoNumbers(10, 3));
Sum: 12, HCF: 4 => [4, 8] Sum: 15, HCF: 5 => [5, 10] Sum: 10, HCF: 3 => No solution exists
Key Points
- The sum must be divisible by the HCF for a solution to exist
- One simple approach is to set one number equal to the HCF
- Multiple solutions may exist, but this method gives the simplest one
- Always validate that the found numbers actually have the required HCF
Conclusion
Finding two numbers from their sum and HCF requires checking divisibility first. The simplest solution sets one number to the HCF itself, ensuring the mathematical relationship holds.
Advertisements
