I have multiple (N) nested loops as follows:
int k = 0;
for (int i1 = 0; i1 < n; i1++)
{
for (int i2 = 0; i2 <= i1; i2++)
{
for (int i3 = 0; i3 <= i2; i3++)
{
...
for (int iN = 0; iN <= i{N-1}; iN++)
{
k++;
//k = f(i1, ... , iN);
}
}
}
}
I need a formula to get k inside the loops based on i1, … , iN.
For N=1: k=f(i1)=i1
For N=2: k=f(i1,i2)=i1*(i1+1)/2+i2
In general, you have a nested sum :
which you can simplify from the inside out using these basic summation formules. The end result will only depend on N as izomorphius commented, as N is the upper limit for i1, which is the upper limit for i2,…
edit: ok, with your edit, I now see you have a different problem in mind. Now it’s a bit more complicated but still no problem.
We will need to split some stuff up for this. I will calculate the value k= f(4,3,1).
At that point in time, we will have performed 4 full i1 loops (i1=0,1,2,3) and are doing the fifth. The k value after 4 full loops of i1(=k_i1) (just before we start the fifth) can be calculated using this function (same kind as before).
Now we start the 5th loop and do the same for the i2 loop. At that point, we will have done 3 full loops of i2 and so we get
This goes on for all your loops. To get the final value, you have to add each of the fi-functions. k will look like
Some minor (+-1) errors in my explanation are possible, but the basic idea is to use the formula to count the full loops.