Euclidean Algorithm implementation written in C#.

### Subtraction-based version:

#### Iterative version:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// ? 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

namespace GCD
{
class Program
{
static void Main(string[] args)
{
int number1;
int number2;

Console.Write("Enter first number: ");

Console.Write("Enter second number: ");

Console.WriteLine("GCD of {0} and {1} is equal to {2}", number1, number2, gcd(number1, number2));
}

static int gcd(int a, int b)
{
while (a != b)
{
if (a > b)
{
a = a - b;
}
else
{
b = b - a;
}
}

return a;
}
}
}

#### Recursive version:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// ? 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

namespace GCD
{
class Program
{
static void Main(string[] args)
{
int number1;
int number2;

Console.Write("Enter first number: ");

Console.Write("Enter second number: ");

Console.WriteLine("GCD of {0} and {1} is equal to {2}", number1, number2, gcd(number1, number2));
}

static int gcd(int a, int b)
{
if (a > b)
{
return gcd(a - b, b);
}
else if (a < b)
{
return gcd(a, b - a);
}
else
{
return a;
}
}
}
}

### Division-based version:

#### Iterative version:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// ? 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

namespace GCD
{
class Program
{
static void Main(string[] args)
{
int number1;
int number2;

Console.Write("Enter first number: ");

Console.Write("Enter second number: ");

Console.WriteLine("GCD of {0} and {1} is equal to {2}", number1, number2, gcd(number1, number2));
}

static int gcd(int a, int b)
{
int t;

while (b != 0)
{
t = b;
b = a % b;
a = t;
}

return a;
}
}
}

#### Recursive version:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// ? 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

namespace GCD
{
class Program
{
static void Main(string[] args)
{
int number1;
int number2;

Console.Write("Enter first number: ");

Console.Write("Enter second number: ");

Console.WriteLine("GCD of {0} and {1} is equal to {2}", number1, number2, gcd(number1, number2));
}

static int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
}
}

C# Euclidean Algorithm
Tagged on: