Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

How to calculate the GCD (greatest common divisor) of two integers in C#

4 Answers

0 votes
using System;
 
class Program
{
    static void Main(string[] args)
    {
        int a = 12, b = 20, gcd = 0;
 
        for (int i = 1; i <= a && i <= b; i++) {
             if (a % i == 0 && b % i == 0)
                 gcd = i;
        }
 
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd);
    }

}


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

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
using System;
 
class Program
{
    static void Main(string[] args)
    {
        int a = 12, b = 20, gcd = 0;
 
        int i = a < b ? a : b;
 
        for (; i <= a && i <= b; i--) {
            if (a % i == 0 && b % i == 0) {
                gcd = i;
                break;
            }
        }
 
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd);
    }
}


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

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
using System;
 
class Program
{
    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static void Main(string[] args)
    {
        int a = 12, b = 20;
 
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd(a, b));
    }
}


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

 



answered May 29, 2017 by avibootz
edited Aug 3, 2023 by avibootz
0 votes
using System;
 
class Program
{
     public static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;

            b = a % b;
            a = temp;
        }
        
        return a;
    }

    static void Main(string[] args)
    {
        int a = 12, b = 20;
 
        Console.WriteLine("The GCD (greatest common divisor) of {0} and {1} is: {2}", a, b, gcd(a, b));
    }
}


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

 



answered Aug 3, 2023 by avibootz
...