1
$\begingroup$

I have this programming challenge I'm doing and I already have code, however I don't really understand it. I think that I need mathematical explanation of how it works, because the code is really easy.

What I'm doing is dividing a number $1 \le N \le 11$ to an array of $12$ elements, so that elements don't differ by more than one. Also when I divide this array into periods of $1$, $2$, $3$, $4$ or $6$ months the number doesn't differ by more than one in these periods.

Here's my algorithm:

d = 12 / N // average length of each interval

for (int i = 0; i < 12; i++){      if (12 - (i % d) > 11) {          array[i] += 1;      } } 

What I really don't understand is this line (12 - (i % d) > 11) . Why does this work ?

1 Answers 1

3

That expression is true iff $i\bmod d$ is zero, i.e. if $i$ is a multiple of $d$. There are $k:=\lceil \frac {12}d\rceil$ such multiples.

If $N$ is a divisor of $12$, then we have exactly $d=\frac {12} N$ and $k=\frac {12}d=N$ as desired.

If $N$ is not a divisor of $12$, then $12=N(d+\theta)$ with $0<\theta<1$ and $k\ge\frac{12}d=N(1+\frac\theta d)>N$ is probably not what you intend. Indeed, with $N=5$, I obtain $d=2$ and the array becaomes $(1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0)$ with $6$ instead of $5$ nonzero entries.