Emulating the Modulus Operator – Solution

In an alternative universe, the C programming language lacks a modulus operator and no companion function exists in the library. What to do! Why, you code your own modulus function, which is the challenge for this month’s Exercise.

For me, the weirdest part about my solution is dealing with remainders of integers. I hope you avoided the temptation to typecast values into real numbers. Yes, this operation can be performed with integers, which is good because integer division does the rounding for you.

Here is my mod() function:

int mod(int x, int y)
{
    return( x-y * (x/y) );
}

The expression in the return statement looks confusing — if you read it left-to-right. Because of the order of operations, the expression is evaluated from right-to-left:

(x/y)

The value of x is divided by y, which is rounded down because these are integer values. The result is the factor of variable y just below variable x. So if 41 and 7 are input as x and y, respectively, the value returned is 5: 5×7 = 35, which is less than 41.

The next step is to multiply the factor by the second value:

y * (x/y)

Don’t be fooled into thinking that the computer calculates x-y first. It does not. Instead, the value of y is multiplied by the result of (x/y), the factor just below variable x. Again, using 41 for x and 7 for y you get the result 35: 7×5 or 7×(41÷7).

Finally, you subtract the result of y * (x/y) from the original value x:

x-y * (x/y)

Using the same values as before: 41 – 7 × (41 ÷ 7). The result is the modulus of 41 and 7.

Here’s the full code for my solution:

2025_01-Exercise.c

/*
   Exercise January 2025
   emulate the % operator
*/
#include <stdio.h>

int mod(int x, int y)
{
    return( x-y * (x/y) );
}

int main()
{
    int a,b;

    printf("Enter two integers separated by a space: ");
    scanf("%d",&a);
    scanf("%d",&b);

    printf("%% operator: %d %% %d = %d\n", a, b, a%b);
    printf("mod() function: %d %% %d = %d\n", a, b, mod(a,b));

    return 0;
}

Obviously, other ways are available to solve this puzzle. I had to wiggle the expression around a few times to get the proper result, which was negative at one point in time. The final expression is short enough to be cryptic, but it works. I hope that your solution met with success.

Leave a Reply