lmdi

导航

第三周作业 --- 阅读程序

这周老师布置了一个阅读程序的作业。

问题如下:

阅读下面程序,请回答如下问题:

问题1:这个程序要找的是符合什么条件的数?

问题2:这样的数存在么?符合这一条件的最小的数是什么?

问题3:在电脑上运行这一程序,你估计多长时间才能输出第一个结果?时间精确到分钟(电脑:单核CPU 4.0G Hz,内存和硬盘等资源充足)。

问题4:在多核电脑上如何提高这一程序的运行效率?

 

using System;

using System.Collections.Generic;

using System.Text;

namespace FindTheNumber

{
  class Program
  {
    static void Main(string[] args)
    {
      int [] rg =
          {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
           20,21,22,23,24,25,26,27,28,29,30,31};
      for (Int64 i = 1; i < Int64.MaxValue; i++)
      {
        int hit = 0;
        int hit1 = -1;
        int hit2 = -1;
        for (int j = 0; (j < rg.Length) && (hit <=2) ; j++)
        {
          if ((i % rg[j]) != 0)
          {
            hit++;
            if (hit == 1)
            {
              hit1 = j;
            }
            else if (hit == 2)
            {
              hit2 = j;
            }
            else
              break;
          }

        }
        if ((hit == 2)&& (hit1+1==hit2))
        {
          Console.WriteLine("found {0}", i);
        }
      }
    }
  }
}

 

  1、通过分析可以知道,代码中hit为数组中数字不能整除i的次数,hit1为第一次不能整除的数的下标,同理hit2为第二次不能整除的数的下标。通过最后一个if判断可知,要找的这个数字i应该是只能被数组内两个数不整除,并且这两个数在数组中相邻。2、上网查了下,Int64.MaxValue的值为18446744073709551615。我不确定这样的数是否存在,我运行了好久没出结果,暂且当成找不到结果。3、由于循环次数过多,以及我所学知识的限制,这个程序的时间复杂度为O(n),但是具体时间却无法确定。4、所学知识有限,不知道如何提高效率。

 

posted on 2016-03-19 18:08  lmdi  阅读(203)  评论(1编辑  收藏  举报