The time complexity is O(n)
because the if
statement has no real effect on that. The complexity of the if
statement is constant over a large enough dataset.
The if
statement may actually do a different amount of work in iterations where you have a multiple of three or five but, the amount of extra work per loop iteration is not dependent on n
. In fact, it averages out to a constant as n
becomes bigger.
And, as an aside, I think that code may be wrong. At multiples of fifteen, it should print both fizz
and buzz
.
If you want to do it to the level in your edit (the added breakdown), you simply need to assign an arbitrary cost ci
to each statement (and this cost is constant for a single execution of that statement) then figure out how many times each statement is run.
For example, the first if
sequence runs n
times, the print "fizz"
runs for one-third of those, n/3
. So you end up with something like this table:
cost times
Fizz-Buzz(n)
for i = 1 to n c1 n
if (n % 3 == 0) c2 n
print "fizz" c3 n / 3 [call this a]
else
if (n % 5 == 0) c4 n - a
print "buzz" c5 (n - a) / 5 [call this b]
else
print n c6 n - a - b
Add up all of those as per your example (substituting the n
-equations for a
and b
) and, in the end, you'll still end up with something dependent on n
, hence an O(n)
algorithm. It'll look something like:
c1*n + c2*n + c3*n/3 + c4*(n-a) + c5*(n-a)/5 + c6*(n-a-b)
= c1*n + c2*n + (c3/3)*n + c4*(n-n/3) + (c5/5)*(n-n/3) + c6*(n-n/3-(n-n/3)/5)
= c1*n + c2*n + (c3/3)*n + c4*(2/3)*n + (c5/5)*(2/3)*n + c6*(n-n/3-(n-n/3)/5)
= c1*n + c2*n + (c3/3)*n + (c4*2/3)*n + (c5*2/15)*n + c6*(n*8/15)
= c1*n + c2*n + (c3/3)*n + (c4*2/3)*n + (c5*2/15)*n + (c6*8/15)*n
/ 1 2 2 8 \
= ( c1 + c2 + - c3 + - c4 + -- c5 + -- c6 ) * n
\ 3 3 15 15 /
All those values inside parentheses are in fact constants (since they're multiples of constants) so the whole thing is a constant multiplier of n
.
Now, if you find a minor mistake in those equations above, I wouldn't be too surprised - I haven't done this level of math for quite a few years, and I may well have thrown in a furphy in case this is for homework and you try copying it verbatim :-)
But the only mistake you're likely to find is the value of the constant multiplier itself. It will still be a constant multiplier of some description, I'll guarantee that.