Find the Best Size Container – Solution

The C library contains various mathematical rounding functions, such as ceil(). That function, however, rounds up floating point values to the next integer. For this month’s Exercise, your job was to round up an integer to multiples of 16: 16, 32, 48, and 64.

In my solution, I had to figure out the difference between the value given and the next increment of 16. To do that, I relied upon my old mathematical pal, the modulus operator, %. The key operation is:

16 - (value % 16)

This statement obtains the difference between a value and the next increment of 16. So if the value is 22, you get 10 as a result, and 22 + 10 = 32. Here’s how that works:

16 - (22 % 16)
16 - (6)
10

The 22 modulo 16 is 6, but 22 + 6 = 28, which isn’t a multiple of 16. So you must subtract 6 from 16 to get 10. That way, when you add the result to the original value, you get: 22 + 10 = 32. And 32 is the next-highest multiple of 16. The full statement is:

value + (16 - value % 16)

An exception must be made for multiples of 16, as you can see in my sample solution here:

#include <stdio.h>

#define COUNT 5

int main()
{
    int lengths[COUNT] = { 4, 28, 52, 16, 35 };
    int x,container;

    for(x=0; x<COUNT; x++)
    {
        if(lengths[x]%16 == 0)
            container = lengths[x];
        else
            container = lengths[x] + (16 - lengths[x]%16);
        printf("Length of %d fits into %d\n",
                lengths[x],
                container);
    }

    return(0);
}

Line 12 tests to see whether the original value, stored in lengths[x], is a multiple of 16. If so, the element is assigned to variable container and displayed in the output (Line 16). If not, the statement at Line 15 determines the value of variable container.

Here’s the output:

Length of 4 fits into 16
Length of 28 fits into 32
Length of 52 fits into 64
Length of 16 fits into 16
Length of 35 fits into 48

One thing I had to keep pounding into my head for this solution was to remember that the modulus operator obtains the remainder, not the difference. The remainder between value and 16 is value % 16. The difference is 16 - value % 16. And you don’t need to use parentheses in that statement because the % operator has higher precedence than the - (subtraction) operator.

As usual, your solution can be different from mine. I’d be curious to see whether anyone devised a solution that didn’t use the modulus operator.

Leave a Reply