C#算法 质因数 最大公约数与最小公倍数

正整数质因数分解:

质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。两个整数相乘,其中这两个数都叫做的因数。

 

    /// <summary>
    /// 正整数质因数分解类
    /// </summary>
    class PrimeFactorization
    {
        private uint number;

        public uint Number
        {
            get { return number; }
            set { number = value; }
        }

        public PrimeFactorization(uint num)
        {
            this.number = num;
        }

        public List<uint> GetPrimeFactor()
        {
            //要返回的质因数
            List<uint> factors = new List<uint>();
            for (uint k = 2; k <= number; k++)//从2开始
            {
                while (true)
                {
                    if (IsPrimes(k) && number % k == 0)
                    {
                        factors.Add(k);
                        number /= k;
                    }
                    else
                    { 
                        break;
                    }
                }
            }
            return factors;
        }

        /// <summary>
        /// 判断是新增的因数是否为质数
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public bool IsPrimes(uint p)
        {
            if (p == 2) return true;
            if (p == 1 || p % 2 == 0) return false;
            for (uint i = 3; i < p; i += 2)//除2以外的质数都是奇数(+2)
            {
                if (p % i == 0) return false;
            }
            return true;
        }
    }

 

            Console.WriteLine("Input a number :");
            uint inputNum = Convert.ToUInt32(Console.ReadLine());
            PrimeFactorization pf = new PrimeFactorization(inputNum);
            List<uint> factors = pf.GetPrimeFactor();
            Console.Write("{0} = ", inputNum);
            for (int i = 0; i < factors.Count-1; i++)
            {
                Console.Write("{0} * ", factors[i]);
            }
            Console.Write("{0}", factors[factors.Count - 1]);

最大公约数与最小公倍数

        /// <summary>
        /// 求两个正整数的最大公约数和最小公倍数
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="gcd"></param>
        /// <param name="lcm"></param>
        public static void GetGCDandLCM(int a, int b, out int gcd, out int lcm)
        {
            int p = a;
            int q = b;
            while (true)
            {
                if (p % q == 0)
                {
                    gcd = q;
                    break;
                }
                else
                {
                    int r = p % q;
                    p = q;
                    q = r;
                }
            }
            lcm = a * b / gcd;
        }
            /*最大公约数与最小公倍数*/
            int gcd, lcm;
            GetGCDandLCM(5, 35, out gcd, out lcm);
            Console.WriteLine("最大公约数为{0},最小公倍数为{1}", gcd, lcm);

 

 

 

posted on 2012-10-04 14:14  YuanSong  阅读(1924)  评论(0编辑  收藏  举报

导航