How to calculate the GCD (greatest common divisor) of two numbers in TypeScript

2 Answers

0 votes
function gcd(a : number, b : number) : number {
    return b == 0 ? a : gcd(b, a % b);
}
  
 
const a = 12, b = 20;
   
console.log("The GCD (greatest common divisor) of " + a + " and " + b + " is: " + gcd(a, b));
 
 

 
 
/*
run:  
 
"The GCD (greatest common divisor) of 12 and 20 is: 4" 
 
*/

 



answered Jan 21, 2022 by avibootz
0 votes
const a = 12, b = 20
let gcd = 0;
        
let i = a < b ? a : b;
    
for (;i <= a && i <= b; i--) {
    if (a % i == 0 && b % i == 0) {
        gcd = i;
        break;
    }
}
    
console.log("The GCD (greatest common divisor) of " + a + " and " + b + " is: " + gcd);
  

  
  
/*
run:  
  
"The GCD (greatest common divisor) of 12 and 20 is: 4" 
  
*/

 



answered Jan 21, 2022 by avibootz
...