~/Home ~/Notes ~/Categories

GCD

2 September, 2020  ·   Dsa Math

LCM and HCF

Factors and multiples:

HCF or GCD :

hcf image

GCD Application : Tiling a rectangle with squares

Naive approach:

1const GCD = (a, b) => {
2  //WKT., Max GCD can be min of two given numbers, so begin with min of a & b.
3  let res = Math.min(a, b);
4  while (res > 0) {
5    if (a % res == 0 && b % res == 0) break;
6    res--;
7  }
8  return res;
9}; //TC : O(min(a,b))

Euclidian Algorithm

The Euclidean algorithm is based on the below facts:

Approach 2 (Euclidian algorithm):

1const GCD = (a, b) => {
2  //stop when a & b are equal and return either of them
3  while (a != b) {
4    if (a > b) a = a - b;
5    else b = b - a;
6  }
7  return a; // or return b;
8};

Optimized euclidian algorithm:

1const GCD = (a, b) => {
2  if (b == 0) return a;
3  else return GCD(b, a % b); //TC :O(log(min(a,b)))
4};

LCM :

Naive approach:

1const lcm = (a, b) => {
2  //LCM would >= larger of 2 numbers 
3  let res = Math.max(a, b);
4  while (res) {
5    if (res % a == 0 && res % b == 0) return res;
6    res++;
7  }
8  return res;
9}; // TC: O(ab-max(a,b))

Efficient soln:

a* b = gcd(a,b) * lcm(a,b)

  • lcm(a,b) = (a*b) / gcd(a*b)
1const lcm = (a, b) => {
2  return (a * b) / GCD(a, b);
3}; //TC: O(log(min(a,b)))
Important properties of LCM and HCF:
 math  ds-algo  programming  competitive-programming
Prime Numbers↠ ↞Factorial