Last active
May 20, 2018 07:19
-
-
Save gushwell/ece89c534be5e1b61511eeeec1893409 to your computer and use it in GitHub Desktop.
C#:最大公約数を求める (ユークリッドの互除法) ref: https://qiita.com/gushwell/items/e9614b4ac2bea3fc6486
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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