Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


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

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|cite|improve this question
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


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

share|cite|improve this answer

Your Answer


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.