**Description:**

There’re `k`

square apple boxes full of apples. If a box is of size `m`

, then it contains `m × m`

apples. You noticed two interesting properties about the boxes:

- The smallest box is of size
`1`

, the next one is of size`2`

,…, all the way up to size`k`

. - Boxes that have an odd size contain only yellow apples. Boxes that have an even size contain only red apples.

Your task is to calculate the difference between the number of red apples and the number of yellow apples.

**Example**

For `k = 5`

, the output should be

`appleBoxes(k) = -15`

.

There are `1 + 3 * 3 + 5 * 5 = 35`

yellow apples and `2 * 2 + 4 * 4 = 20`

red apples, thus the answer is `20 - 35 = -15`

.

**Input/Output**

**[time limit] 3000ms (cs)**

**[input] integer k**A positive integer.

*Constraints:*

`1 ≤ k ≤ 40`

.**[output] integer**The difference between the two types of apples.

**Tests:**

**Solution:**

int appleBoxes(int k) { if(1 <=k && k <= 40) { int yellows=0; int reds=0; for(int index=1;index<=k;index++) { if(index%2==0) { reds+=index*index; } else { yellows+=index*index; } } return reds-yellows; } else { throw new ArgumentOutOfRangeException(); } }

Advertisements

int sum =0;

for (int i=1;i<=k;i++) sum+=i*i*(1-i%2*2);

return sum;

LikeLike