Apple Boxes

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:

  1. The smallest box is of size 1, the next one is of size 2,…, all the way up to size k.
  2. 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

One thought on “Apple Boxes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s