算法运行时复杂度

时间:2010-07-09 13:15:38

标签: c#

您好我想编写一个显示运行时complixity的程序 我解决了两个但是无法解决第三个代码是:

{
class Program
{
    /* static long F1(long n)
     {
         long sum = 0;
         for (int k = 1; k <= n; k++)
         {
             for (int j = 1; j <=n*n; j++)
             {
                 for (int m = 1; m <=j; m++)
                 {
                     sum = sum + 1;
                 }
             }
         }
         return sum;
      }
    static long F2(long n)
     {
         long sum = 0;
         for (int k = 1; k <= n; k++)
         {
             for (int j = 1; j <= n ; j++)
             {
                 for (int m = 1; m <= j; m++)
                 {
                     sum = sum + 1;
                 }
             }
         }
         return sum;

     }*/
  static long F3(long n)
  {
      long prod = 1;
      long m;
      long i = 2;
      long s = n;
      while (n >= 1)
      {
          m = 1;
          while (m <= n)
          {
              prod = prod * 2;
              m = m + 1;
          }
          n = s / i;
          i++;
      }
         return prod;

     }


    static void Main(string[] args)
    {
       // Console.WriteLine(F1(100));
       // Console.WriteLine(F2(2200));
     Console.WriteLine(F3(10000));
        long x; 
        DateTime d1=DateTime.Now;
        x=d1.Ticks;
     // F1(600);  
    //    F2(2200);
        F3(1000);
        DateTime d2=DateTime.Now;
        x=(d2.Ticks-x)/10000000;
        Console.WriteLine("x=" + x.ToString());
        Console.ReadLine();
    }
}

}

now the correct answers that F3 should show are

300000000   0   5
400000000   0   4
500000000   0   7

但我得到的只是o o o

虽然F2和F1显示正确的答案可以任何一个帮助

2 个答案:

答案 0 :(得分:1)

我想知道的是:这不仅仅是整数除法的问题吗?

我的意思是:x=(d2.Ticks-x)/10000000;

注意:我对C#不实用,这只是一个假设

答案 1 :(得分:0)

 x=(d2.Ticks-x)/10000000

是问题所在。 F3运行不到一秒钟,你正在进行整数除法:记住900/1000 == 0

一个简单(相当不优雅)的修复方法是进行浮点除法:

 x=(d2.Ticks-x)/10000000.0

您可能希望使用TimeSpan的intead来衡量已用时间:

DateTime start = DateTime.Now;

// Do stuff

DateTime end = DateTime.Now;
TimeSpan elapsed = end - start;
double secondsElapsed = elapsed.TotalSeconds;