加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

找10个最小的连续的合数

(2010-12-28 21:34:21)
标签:

最小

连续合数

分类: 技术总结
    /// <summary>
    /// 找10个最小的连续的合数
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            int findCount = 10;
            int count = 0;
            int x = 1;
            //不知道啥时候是个头,所以true
            while (true)
            {
                //从x开始找10个数,逐一判断是否是合数
                for (int i = x; i < x + findCount; i++)
                {
                    //如果其中有一个是素数
                    if (p.IsPrime(i) == true)
                    {
                        //Console.WriteLine("begin:{0},end:{1},count:{2}",x,x+count,count);
                        //那么连续就中断了
                        //计数也得从0开始了
                        count = 0;
                        //将起始值设置为i
                        x = i ;
                        break;
                    }
                    else
                    {
                        //如果是合数,那么计数加一
                        count++;
                    }
                }
                //要是跳出来的时候计数是10,那么整个循环就可以结束了
                if (count == findCount)
                {
                    break;
                }
                else
                {
                    //否则将x加一,继续找后10个数来尝试
                    x++;
                }
            }
            //打印找到的那几个数
            for (int i = x; i < x + findCount; i++)
            {
                Console.WriteLine("{0}={1}", i, p.GetFactor(i));
            }
            
        }
        /// <summary>
        /// 判断某个数是否是素数
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        bool IsPrime(int x)
        {
            for (int i = 2; i < x; i++)
            {
                if (x % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 得到某个数的因式分解
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        string GetFactor(int x)
        {
            //每个数都有1为因数
            string result = "1*";
            //从2开始
            for (int i = 2; i <= x; )
            {
                //如果可以被i整除
                if (x%i==0)
                {
                    //那么结果中加上这个数
                    result += i.ToString()+"*";
                    //将x整除,将整除的结果给x,再次计算
                    x = x / i;
                }
                else
                {
                    i++;
                }
            }
            //去掉最后一个*
            return result.Substring(0, result.Length - 1); ;
        }
    }

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有