The precise general expression for the sequence generated by my code From the following code, I would like to extract the general formula in terms of $n$
   public static int second_loop(int n ){
        int count = 0;
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                for(int k=i; k<=2*j - 1; k++)
                    count++;
        return count;
    }

I manage to get the following approximation: 0.5 * n^2 * (n + 1).
Comparing the values that I got from the approximation above with the count (i.e., expected value) from the code, I got the following:
       expected value | approximation 
N=1 |         1       |    1
N=2 |         6       |    6 
N=3 |        19       |    18
N=4 |        43       |    40
N=5 |        82       |    75

However, the approximation is wrong. Someone has tried to help me answer it but it’s still wrong.
My question is how can I get the precise expression?
I am not working or study math at the moment so this question might be super simple to solve, but unfortunately not for me.
 A: The code can be translated thus
$$\sum_{j=1}^N\sum_{i=1}^{\max(2j-1,N)}\left(2j-i\right).
$$
Now let $N = 2m$ then $2j-1<N$ is equivalent to $j\le m$. So we split the sum:
$$\begin{align}
&\sum_{j=1}^m\sum_{i=1}^{2j-1}(2j-i) + \sum_{j=m+1}^{2m}\sum_{i=1}^{N}(2j-i) \\
&= \sum_{j=1}^m \left((2j)(2j-1)-\frac{(2j-1)(2j)}{2}\right) + \sum_{j=m+1}^{2m} \left(2jN-\frac{N(N+1)}{2}\right) \\
&= \sum_{j=1}^m\left( 2j^2 - j \right) + \left(2\cdot 2m\left(\sum_{j=1}^{2m}j-\sum_{j=1}^m j\right) - \frac{2m(2m+1)}{2}\cdot m\right)\\
&= 2 \left(\frac{m(m+1)(2m+1)}{6} \right) - \frac{m(m+1)}{2} + \left(2m(4m^2+2m-(m^2+m))-m(2m+1)(m)\right)\\
&= m(m+1)\left(\frac{2m+1}{3}-\frac12\right) + \left(2m(3m^2+m)-m^2(2m+1)\right)\\
&= \frac16(m)(m+1)(4m-1)+m^2(4m+1)\\
&=\frac16 m(28m^2+9m-1).
\end{align}$$
Now you should do the case of $N=2m+1$, and noting that 2j-1<N is also equivalent to $j\le m$. Then, the first sum is the same as above.
A: Correcting the typos in my comment:
Your sum is $$\sum_{i=1}^n \sum_{j=1}^n \sum_{k=i}^{2j-1} 1  = \sum_{j=1}^n \sum_{i=1}^{\max(2j, n)} (2j-i)$$ Splitting the $j$ sum into parts where $2j\leq n$ and $2j>n$, using the formulas for $\sum j$ and $\sum j^2$, and conditioning on whether $n$ is odd or even, the sum is $(28m^3 + 9m^2 - m)/6$ if $n=2m$ (values 6, 43, 139, ...) and $(m + 1) (28 m^2  + 23 m + 6)/6$ if $n=2m+1$ (values 1, 19, 82, ...).
For example, if $n=2m+1$ then the sum is $\sum_{j=1}^m \sum_{i=1}^{2j} (2j-i) + \sum_{j=m+1}^{2m+1} \sum_{i=1}^n (2j-i)$. The sum from $i=1$ to $2j$ of $(2j-i)$ is $j(2j-1)$ and the sum from $i=1$ to $n$ of $(2j-i)$ is $2jn-n(n+1)/2$, so we get
$$ \sum_{j=1}^m j(2j-1) + \sum_{j=m+1}^{2m+1}(2jn-n(n+1)/2)$$
Using the sum-of-squares formula, this is
$$ m(m+1)(2m+1)/3 - m(m+1)/2 + 2(2m+1)(m+1)(3m+2)/2 - (m+1)^2(2m+1) $$
which simplifies to $(m+1)(28m^2+23m+6)/6$.
