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

1 Answer

0 votes
class MyClass
{
    static int gcd(int a, int b) {
        var  gcd = 0;
        
        for (var  i = 1; i <= a && i <= b; i++) {
            if (a % i == 0 && b % i == 0) {
                gcd = i;
            }
        }
        return gcd;
    }
    
    static void main()
    {
        var  a = 12;
        var  b = 20;
        
        var result = gcd(a, b);
        
        print("The GCD (greatest common divisor) of $a and $b is: $result");
    }
}

void main() {
	MyClass.main();
}



/*
run:

The GCD (greatest common divisor) of 12 and 20 is: 4

*/

 



answered Apr 27, 2023 by avibootz
...