Example of O(n!)?

后端 未结 16 2475
渐次进展
渐次进展 2020-11-30 22:20

What is an example (in code) of a O(n!) function? It should take appropriate number of operations to run in reference to n; that is, I\'m asking a

16条回答
  •  余生分开走
    2020-11-30 22:54

    You are right the recursive calls should take exactly n! time. here is a code like to test factorial time for n different values. Inner loop runs for n! time for different values of j, so the complexity of inner loop is Big O(n!)

    public static void NFactorialRuntime(int n)
        {
            Console.WriteLine(" N   Fn   N!");
            for (int i = 1; i <= n; i++)  // This loop is just to test n different values
            {
                int f = Fact(i);
                for (int j = 1; j <= f; j++)  // This is Factorial times
                {  ++x; }
                Console.WriteLine(" {0}   {1}   {2}", i, x, f);
                x = 0;
            }
        }
    

    Here are the test result for n = 5, it iterate exactly factorial time.

      N   Fn   N!
      1   1   1
      2   2   2
      3   6   6
      4   24   24
      5   120   120
    

    Exact function with time complexity n!

    // Big O(n!)
    public static void NFactorialRuntime(int n)
        {
            for (int j = 1; j <= Fact(i); j++) {  ++x; }
            Console.WriteLine(" {0}   {1}   {2}", i, x, f);
        }
    

提交回复
热议问题