Skip to content

Instantly share code, notes, and snippets.

@gushwell
Last active May 20, 2018 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gushwell/ece89c534be5e1b61511eeeec1893409 to your computer and use it in GitHub Desktop.
Save gushwell/ece89c534be5e1b61511eeeec1893409 to your computer and use it in GitHub Desktop.
C#:最大公約数を求める (ユークリッドの互除法) ref: https://qiita.com/gushwell/items/e9614b4ac2bea3fc6486
class Program {
static void Main(string[] args) {
Console.WriteLine(Gcd(0, 8));
Console.WriteLine(Gcd(12, 8));
Console.WriteLine(Gcd(3400, 6596));
Console.WriteLine(Gcd(12707, 12319));
}
// ユークリッドの互除法
public static int Gcd(int a, int b) {
if (a < b)
// 引数を入替えて自分を呼び出す
return Gcd(b, a);
while (b != 0) {
var remainder = a % b;
a = b;
b = remainder;
}
return a;
}
}
public static int Gcd(int a, int b) {
return a > b ? GcdRecursive(a, b) : GcdRecursive(b, a);
}
private static int GcdRecursive(int a, int b) {
return b == 0 ? a : GcdRecursive(b, a % b);
}
public static int Gcd(int a, int b) {
Func<int, int, int> gcd = null;
gcd = (x, y) => y == 0 ? x : gcd(y, x % y);
return a > b ? gcd(a, b) : gcd(b, a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment