アルゴとリズム

ユークリッドの互除法

久しぶりにC#を触るので、とりあえずユークリッドの互除法を作ってみました。
コンソール版とフォーム版があります。

EuclideanAlgorithm.cs

namespace ユークリッドの互除法
{
    public class EuclideanAlgorithm
    {
        public int Exec(int m, int n)
        {
            if (m < n)
            {
                int tmp = m;
                m = n;
                n = tmp;
            }

            while (n > 0)
            {
                int tmp = n;
                n = m % n;
                m = tmp;
            }

            return m;
        }
    }
}

Console.cs

using System;

namespace ユークリッドの互除法
{
    class Console
    {
        static void Main(string[] args)
        {
            int m = Convert.ToInt32(args[0]);
            int n = Convert.ToInt32(args[1]);

            System.Console.WriteLine((new EuclideanAlgorithm()).Exec(m, n));
        }
    }
}

Form.cs

using System;

namespace ユークリッドの互除法
{
    public partial class Form : System.Windows.Forms.Form
    {
        public Form()
        {
            InitializeComponent();
        }

        private void TextChangedHandler(object sender, EventArgs e)
        {
            int m;
            int n;

            string result = "";

            if (Int32.TryParse(txtM.Text, out m) &&
                Int32.TryParse(txtN.Text, out n))
            {
                result = (new EuclideanAlgorithm()).Exec(m, n).ToString();
            }

            txtResult.Text = result;
        }
    }
}

FizzBuzz

じゃあ、FizzBuzz でも作ってみるかな、と。
yield 使ってるトコが C# ぽいですか。

FizzBuzz.cs

using System.Collections;

namespace FizzBuzz
{
    public class FizzBuzz
    {
        public static IEnumerable GetValue()
        {
            for (int i = 1; i <= 100; i++)
            {
                if      (i % 15 == 0) yield return "FizzBuzz";
                else if (i %  5 == 0) yield return "Buzz";
                else if (i %  3 == 0) yield return "Fizz";
                else                  yield return i;
            }
        }
    }
}

Console.cs

namespace FizzBuzz
{
    class Console
    {
        static void Main(string[] args)
        {
            foreach (object o in FizzBuzz.GetValue())
                System.Console.WriteLine(o);
        }
    }
}

Form.cs

namespace FizzBuzz
{
    public partial class Form : System.Windows.Forms.Form
    {
        public Form()
        {
            InitializeComponent();

            foreach (object o in FizzBuzz.GetValue())
                listBox1.Items.Add(o);
        }
    }
}