1

I have this code and I am trying to work out the time complexity of it when n=2, n=4 and n=6. Can anyone help me? I'm confused as how I do it? Big-O Notation please.

using System;

class TimeComplexityTest
{
    public static void Main( string[] args)
    {
        int n;

        Console.WriteLine("Please enter the value of n");
        n = Int32.Parse(Console.ReadLine()); 
        Console.Write("\n");

        for (int i = 1; i <= 1.5*n; i++)
            Console.WriteLine(i);
        for (int i = n; i >= 1; i--)
            Console.WriteLine(i);

        Console.Read();
    }
}
6
  • miissing some curly brackets? the time complexity shouldnt change with n surely? Commented Mar 7, 2015 at 12:24
  • What exactly do you want - the algorithm complexity in big-O notation or just time in milliseconds for your piece of code? Commented Mar 7, 2015 at 12:25
  • 1
    o(n) surely? but shouldn't the loops be nested? Commented Mar 7, 2015 at 12:26
  • Yeah, I was thinking O(N), but I'm just a learner and wasn't sure... Thanks. Commented Mar 7, 2015 at 12:34
  • 1
    Note that "the time complexity for n = 2, 4, 6..." does not really make sense: Time complexity describes the dependency of the run time as a function of n so it is not really relevant what it looks like for particular values of n - what is relevant is how is scales -- e.g. if n doubles, does the run time stay approximately the same, does it double, or even quadruple, for instance. This is what the Big O-notation expresses. Commented Mar 7, 2015 at 13:12

1 Answer 1

4

You have 2 loops: one running 1.5n times, and the other running 1n times. The time complexity for that is 2.5n, which is O(n).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.