[ACM]Q10329: Combinatorial Expression

[ACM]Q10329: Combinatorial Expression


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace Q10329
{
    class Program
    {
        static private int[] nm, rs; static private char[] par = { ' ' }; static private int times, count, temp;
        static private BigInteger t1, t2; static private BigInteger[] bi;
        static void Main(string[] args)
        {
            for (; ; )
            {
            labelnm: Console.Write("n m>>>");
                try
                {
                    nm = Array.ConvertAll<string, int>(Console.ReadLine().Split(par, StringSplitOptions.RemoveEmptyEntries), int.Parse);
                    if (nm.Length != 2) throw new Exception();
                }
                catch { goto labelnm; }
                times = nm[0] + nm[1]; count = 0;
                bi = new BigInteger[times];
                while (count < times)
                {
                labelrs: Console.Write("r s>>>");
                    try
                    {
                        rs = Array.ConvertAll<string, int>(Console.ReadLine().Split(par, StringSplitOptions.RemoveEmptyEntries), int.Parse);
                        if (rs.Length != 2 || rs[0] < rs[1]) throw new Exception();
                    }
                    catch { goto labelrs; }
                    temp = rs[1] > rs[0] - rs[1] ? rs[0] - rs[1] : rs[1];
                    t1 = t2 = 1;
                    for (int i = 0; i < temp; i++)
                    {
                        t1 *= (rs[0] - i);
                        t2 *= (i + 1);
                        BigInteger gcd = GCD(t1, t2);
                        t1 /= gcd;
                        t2 /= gcd;
                    }
                    bi[count] = t1 / t2;
                    count++;
                }
                t1 = t2 = 1;
                for (int i = 0; i < times; i++)
                {
                    if (i < nm[0])
                    {
                        t1 *= bi[i];
                    }
                    else
                    {
                        t2 *= bi[i];
                    }
                }
                if ((t1 / t2).ToString().Length >= 100)
                    Console.WriteLine("Ans=-1");
                else if (t1 % t2 == 0)
                    Console.WriteLine("Ans={0}", t1 / t2);
                else if (t1 % t2 != 0)
                    Console.WriteLine("Ans=0");
            }
        }
        static public BigInteger GCD(BigInteger x, BigInteger y)
        {
            //if (x < y) { x = x ^ y; y = x ^ y; x = x ^ y; }
            if (x == y) return x;
            while (true)
            {
                if (x > y) { x = x % y; if (x == 0)return y; }
                else if (x < y) { y = y % x; if (y == 0)return x; }
                else return x;
                if (x == 1 || y == 1) return 1;
            }
        }
    }
}