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
2010-04-18 03:21:31
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
2010-04-18 07:08:03
+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
2010-04-18 03:23:20
+5
A:
Simple:
If the quotient
a/b
is representable, the expression(a/b)*b + a%b
shall equala
(C99 standard, 6.5.5/6).
James McNellis
2010-04-18 03:23:23
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
2010-04-18 08:17:15
@Clifford: Maybe because with an obvious transformation (subtract `(a/b)*b` from both sides) it becomes a formula for determining `a%b`?
caf
2010-04-18 08:49:53
@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
2010-04-18 15:24:23