Easy

You have k apple boxes full of apples. Each square box of size m contains m × m apples. You just noticed two interesting properties about the boxes:

  1. The smallest box is size 1, the next one is 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, making the answer 20 - 35 = -15.

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] integer k

    A positive integer.

    Guaranteed constraints:
    1 ≤ k ≤ 40.

  • [output] integer

    • The difference between the two types of apples.

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

int appleBoxes(int k)
{
	int apple=0;

	for(int i=1;i<=k;i++)
		apple+=i%2==0?i*i:-i*i;

	return apple;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> Rounders  (0) 2020.04.13
<Codesignal> Increase Number Roundness  (0) 2020.04.12
<Codesignal> Addition Without Carrying  (0) 2020.04.12
<Codesignal> Lineup  (0) 2020.04.12
<Codesignal> Magical Well  (0) 2020.04.12

+ Recent posts