From d914bd904150e8a9486c9c2728b5cb08e772f82b Mon Sep 17 00:00:00 2001 From: Novojit Saha <55886194+redfly1@users.noreply.github.com> Date: Wed, 6 May 2020 18:27:22 +0600 Subject: [PATCH] added hcf finding algorithm (#104) * added hcf finding algorith * Update and rename find_hcf.js to FindHcf.js Co-authored-by: vinayak --- maths/FindHcf.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 maths/FindHcf.js diff --git a/maths/FindHcf.js b/maths/FindHcf.js new file mode 100644 index 000000000..f6b696219 --- /dev/null +++ b/maths/FindHcf.js @@ -0,0 +1,30 @@ +/* + author: redfly1 + More about HCF: + https://en.wikipedia.org/wiki/Greatest_common_divisor + */ + +function findHCF (x, y) { + // If the input numbers are less than 1 return an error message. + if (x < 1 || y < 1) { + return 'Please enter values greater than zero.' + } + + // If the input numbers are not integers return an error message. + if (x !== Math.round(x) || y !== Math.round(y)) { + return 'Please enter whole numbers.' + } + + // Now apply Euclid's algorithm to the two numbers. + while (Math.max(x, y) % Math.min(x, y) !== 0) { + if (x > y) { + x %= y + } else { + y %= x + } + } + + // When the while loop finishes the minimum of x and y is the HCF. + return Math.min(x, y) +} +console.log(findHCF(27, 36))