Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 17 additions & 27 deletions Maths/GetEuclidGCD.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,22 @@
/*
Problem statement and Explanation : https://en.wikipedia.org/wiki/Euclidean_algorithm
In this method, we have followed the iterative approach to first
find a minimum of both numbers and go to the next step.
*/

/**
* GetEuclidGCD return the gcd of two numbers using Euclidean algorithm.
* @param {Number} arg1 first argument for gcd
* @param {Number} arg2 second argument for gcd
* @returns return a `gcd` value of both number.
* GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers
* @param {Number} a integer (may be negative)
* @param {Number} b integer (may be negative)
* @returns {Number} Greatest Common Divisor gcd(a, b)
*/
const GetEuclidGCD = (arg1, arg2) => {
// firstly, check that input is a number or not.
if (typeof arg1 !== 'number' || typeof arg2 !== 'number') {
return new TypeError('Argument is not a number.')
export function GetEuclidGCD (a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('Arguments must be numbers')
}
// check that the input number is not a negative value.
if (arg1 < 1 || arg2 < 1) {
return new TypeError('Argument is a negative number.')
a = Math.abs(a)
b = Math.abs(b)
if (a === 0 && b === 0) return undefined // infinitely many numbers divide 0
if (a < 0) a = -a
if (b < 0) b = -b
while (b !== 0) {
const rem = a % b
a = b
b = rem
}
// Find a minimum of both numbers.
let less = arg1 > arg2 ? arg2 : arg1
// Iterate the number and find the gcd of the number using the above explanation.
for (less; less >= 2; less--) {
if ((arg1 % less === 0) && (arg2 % less === 0)) return (less)
}
return (less)
return b
}

export { GetEuclidGCD }