Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Algorithm:

for (int i = 0; i < 2*n; i += 2)  
    for (int j = n; j >i; j--)  
        foo();

I want to find the number of times foo() is called.

# of foo() calls for the second loop as i changes:

1st loop:   n - 0
2nd loop:   n - 2
3rd loop:   n - 4
nth loop:   n - f(x); f(x) = last term +2; where f(0) = 0

  Total # calls = Summation(n - f(x)) from [i = 0] to [i = n/2 (where f(x) == n)]
= Summation(n) - summation(f(x))
= (n/2)(n+n)/2 - (n/2)(0 + n)/2
= n^2/2        - n^2/4
= n^2/4

I've done all the work but my equation always gives values that are a bit off.
What have I done wrong?

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

The summation has $n/2+1$ terms; i=0 is the first term and i=n/2 is the last one! So you should have

summation(n) = (n/2+1) (n+n)/2

and

summation(f(x)) = (n/2+1) (0+n)/2.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.