# find the greatest common divisor of two numbers in typescript

Here is an implementation of the Euclidean algorithm in TypeScript to find the greatest common divisor (GCD) of two numbers:

index.ts
function gcd(a: number, b: number): number {
// ensure a >= b
if (b > a) {
[a, b] = [b, a];
}

// find gcd using Euclidean algorithm
while (b !== 0) {
let remainder = a % b;
a = b;
b = remainder;
}

return a;
}
279 chars
16 lines

The above function takes two parameters a and b, which are the two numbers for which the GCD is to be calculated. The implementation first ensures that a is greater than or equal to b, as the algorithm requires. It then finds the GCD using the Euclidean algorithm, which repeatedly divides the larger number by the smaller number and takes the remainder until the remainder is 0. The final value of the smaller number is the GCD.

You can call this function like so:

index.ts
let a = 20, b = 30;
let result = gcd(a, b);
console.log(`The GCD of \${a} and \${b} is \${result}`);
98 chars
4 lines

This will output:

index.ts
The GCD of 20 and 30 is 10
27 chars
2 lines

### related categories

gistlibby LogSnag