From b29f95310c742fc24e2ad1fe8a0b1ad5694b11d5 Mon Sep 17 00:00:00 2001 From: Mohit Sharma Date: Sat, 16 Sep 2017 21:14:16 +0530 Subject: [PATCH] Implemented Eucledian GCD --- Algorithms/EucledianGCD.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Algorithms/EucledianGCD.js diff --git a/Algorithms/EucledianGCD.js b/Algorithms/EucledianGCD.js new file mode 100644 index 0000000000..7184719d10 --- /dev/null +++ b/Algorithms/EucledianGCD.js @@ -0,0 +1,37 @@ +function euclideanGCDRecursive (first, second) { + /* + Calculates GCD of two numbers using Euclidean Recursive Algorithm + :param first: First number + :param second: Second number + :return: GCD of the numbers + */ + if (second === 0) { + return first; + } else { + return euclideanGCDRecursive(second, (first % second)); + } +} + +function euclideanGCDIterative (first, second) { + /* + Calculates GCD of two numbers using Euclidean Iterative Algorithm + :param first: First number + :param second: Second number + :return: GCD of the numbers + */ + while (second !== 0) { + var temp = second; + second = first % second; + first = temp; + } + return first; +} + +function main () { + var first = 20; + var second = 30; + console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second)); + console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second)); +} + +main();