網頁

Friday, December 10, 2010

[C#] 三數最大公因數

很久沒玩這種東西了,一開始我還很老實地想慢慢算XD,後來才發現解法可以超簡單。

隨便列一下程式碼。
        private void button1_Click(object sender, EventArgs e)
        {
            int N1,N2,N3;

            if (IsNumeric(textBox1.Text) && IsNumeric(textBox2.Text) && IsNumeric(textBox3.Text))
            {
                N1 = Convert.ToInt32(textBox1.Text);
                N2 = Convert.ToInt32(textBox2.Text);
                N3 = Convert.ToInt32(textBox3.Text);

                int N4 = gcd(N1, N2);
                label1.Text = gcd(N4, N3).ToString();
            }
        }

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

        static bool IsNumeric(object Expression)
        {
            bool isNum;

            double retNum;

            isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
            return isNum;
        }

No comments:

Post a Comment