views:

220

answers:

4

How can we implement the modulo operator as a function in C without using the operator?

+10  A: 

Do an integer division followed by a multiplication, and subtract.

#include <stdio.h>
int main()
{
  int c=8, m=3, result=c-(c/m*m);
  printf("%d\n", result);
}
Ignacio Vazquez-Abrams
A: 

Here you go:

a % b = a - (b * int(a/b))
fbrereto
That cast notation only works in C++ (not C, which the question asks about) and is superfluous if a and b are integers. But the downvote came from elsewhere.
Jonathan Leffler
+1  A: 

You could simulate x % y by repeatedly subtracting y from x and keeping track of the result. At each iteration, if the result is less than y, then you have your remainder, and can just return it.

Justin Ethier
+5  A: 

Simple:

If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a

(C99 standard, 6.5.5/6).

James McNellis
This does not directly answer the question, it is merely an axiomatic definition of the % operator (and therefore not really "simple"). I am wondering at the number for votes for this.
Clifford
@Clifford: Maybe because with an obvious transformation (subtract `(a/b)*b` from both sides) it becomes a formula for determining `a%b`?
caf
@caf: Maybe, but "simple" would have been to present the "obvious" transformation rather than assume the reader possesses the (albeit basic) mathematical skills. The mathematical ability of the OP is unknown; to assume that it is obvious may just look like showing off.
Clifford