Updated to reflect the question "Actually what I'm searching is an answer to the following question: given m
, if suddenly I interrupt the cycle in a point where g
and h
has some specific value, e.g. g=2
and h=3
, what is the value assumed by cont
?" given in a comment.
If we stop the execution at the point where g = g'
and h = h'
, we can represent that using the following algorithm:
cont = 0
for g = 1,...,g' - 1
for h = g,...,m
cont = cont + 1
end for
end for
for h = g',..., h'
cont = cont + 1
end for
(I'm assuming we stop execution after cont = cont + 1
is executed one last time. If that's not desired, you can simply subtract 1 from the final answer.)
We can do the same thing again:
cont = 0
for g = 1,...,g' - 1
cont = cont + m - g + 1
end for
cont = cont + h' - g' + 1
Factor out the constants for simplicity:
cont = (g' - 1) * (m + 1) + h' - g' + 1
for g = 1,...,g' - 1
cont = cont - g
end for
And we can use the triangle number trick again now:
cont = (g' - 1) * (m + 1) + h' - g' + 1 - (g' - 1) * g' / 2
Rearranging everything to get the final closed-form formula:
cont = (g' - 1) * (m - g' / 2) + h'
The original answer
As @Caleth mentioned, m
is the only free variable in your code.
First:
for a = 1,...,b
cont = cont + 1
end for
is equivalent to
cont = cont + b
And by extension:
for h = g,...,m
cont = cont + 1
end for
is equivalent to
cont = cont + m - g + 1
We can now simplify the code to:
cont = 0
for g = 1,...,m
cont = cont + m - g + 1
end for
Factoring out the parts that don't depend on g
:
cont = m * (m + 1)
for g = 1,...,m
cont = cont - g
end for
we can change that to:
cont = m * (m + 1)
subtract = 0
for g = 1,...,m
subtract = subtract + g
end for
cont = cont - subtract
You can now see that the final values of subtract
for consecutive values of m
for the triangular numbers. Wikipedia says n * (n + 1) / 2
as a closed-form formula for the n
th triangle number. Plugging that in gives:
we can change that to:
cont = m * (m + 1)
subtract = m * (m + 1) / 2
cont = cont - subtract
which means we end up with:
cont = m * (m + 1) / 2
g
andh
in a coordinate system, and marking those where the counter is incremented. You'll find that the relevant cases form one half of a rectangle. That should tell you what the total number of increments is.g
andh
are defined within that code,m
is the only inputm*(m+1)/2
) but I want to find the map that returns the value ofcont
in giveng
andh
. For example, ifm=3
, what is the value ofcont
at the iteration withg=2
andh=3
?(g, h, count)
tuples? Or a function that - unlike the one you sketched - maps(m, g, h) -> count
?m
,g
,h
compute the value ofcount
. I'm sorry for my imprecision, I hope to have clarified my problem.