diff options
author | Igor <pashev.igor@gmail.com> | 2011-01-12 15:33:44 +0300 |
---|---|---|
committer | Igor <pashev.igor@gmail.com> | 2011-01-12 15:33:44 +0300 |
commit | cb9ab4e10b97f91bcf78fc643821851097a54e7e (patch) | |
tree | ac08985c2e405a77d7599f0934561cb6acdbd603 | |
download | gcd-cb9ab4e10b97f91bcf78fc643821851097a54e7e.tar.gz |
Begin: C, C#, Haskell, Java, Python
-rw-r--r-- | gcd.c | 46 | ||||
-rw-r--r-- | gcd.cs | 32 | ||||
-rw-r--r-- | gcd.hs | 14 | ||||
-rw-r--r-- | gcd.java | 28 | ||||
-rwxr-xr-x | gcd.py | 18 |
5 files changed, 138 insertions, 0 deletions
@@ -0,0 +1,46 @@ +#include <stdlib.h> +#include <stdio.h> + +unsigned int gcd2(unsigned int a, unsigned int b) +{ + unsigned int c; + while (b != 0) { + c = b; + b = a % b; + a = c; + } + return a; +} + +unsigned int gcdn(unsigned int a[], size_t n) +{ + unsigned int r; + size_t i; + r = a[0]; + for(i = 1; i < n; i++) { + r = gcd2(r, a[i]); + } + return r; +} + + +int main (int argc, char *argv[]) +{ + unsigned int *a; + int i, n; + + if (argc > 1) { + n = argc - 1; + a = malloc(sizeof(unsigned int) * n); + if (NULL != a) { + for (i = 1; i <= n; i++) + a[i-1] = atoi(argv[i]); + printf("%u\n", gcdn(a, n)); + free(a); + return EXIT_SUCCESS; + } + return EXIT_FAILURE; + } + return EXIT_SUCCESS; +} + @@ -0,0 +1,32 @@ +using System; + +namespace GCD { + class Program { + static uint gcd2(uint a, uint b) { + uint c; + while (b != 0) { + c = b; + b = a % b; + a = c; + } + return a; + } + + static uint gcdn(uint [] n) { + uint r = n[0]; + for (int i = 1; i < n.Length; i++) + r = gcd2(r, n[i]); + return r; + } + + static void Main(string [] argv) { + uint [] a = Array.ConvertAll<string, uint>(argv, + new Converter<string, uint> + (delegate(string s) {return uint.Parse(s);}) + ); + + Console.WriteLine("{0}", gcdn(a)); + } + } +} + @@ -0,0 +1,14 @@ +import System(getArgs) + +gcd2 a 0 = a +gcd2 a b = gcd2 b (rem b a) + +gcdn n = foldl1 gcd2 n + +str2int :: String -> Integer +str2int = read + +main = do + a <- getArgs + print (gcdn (map str2int a)) + diff --git a/gcd.java b/gcd.java new file mode 100644 index 0000000..3c174aa --- /dev/null +++ b/gcd.java @@ -0,0 +1,28 @@ +public class gcd +{ + public static int gcd2(int a, int b) { + int c; + while (b != 0) { + c = b; + b = a % b; + a = c; + } + return a; + } + + public static int gcdn(int [] a) { + int r = a[0]; + for (int i = 1; i < a.length; i++) + r = gcd2(r, a[i]); + return r; + } + + public static void main(String [] argv) { + int [] n = new int [argv.length]; + for (int i = 0; i < argv.length; i++) { + n[i] = Integer.parseInt(argv[i]); + } + System.out.println(gcdn(n)); + } +} + @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 + +import sys +import functools + +def gcd2(a, b): + if b == 0: + return a + else: + return gcd2(b, a % b) + +def gcdn(ns): + return functools.reduce(gcd2, ns) + +ints = map(int, sys.argv[1:]) +gcd = gcdn(ints) +print(gcd) + |