How to find modulus without using modulus operator

Programming

Modulus Operator %

It is used to find remainder, check whether a number is even or odd etc.
Example:


7 % 5 = 2	Dividing 7 by 5 we get remainder 2.
4 % 2 = 0	4 is even as remainder is 0.

Computing modulus

Let the two given numbers be x and n.
Find modulus (remainder)
x % n
Example
Let x = 27 and n = 5


Step 1
Find quotient (integer part only)
q = x / n

Example
q = 27 / 5 = 5	(taking only the integer part)

Step 2
Find product
p = q * n

Example
p = 5 * 5 = 25

Step 3
Find modulus (remainder)
m = x - p

Example
m = 27 - 25 = 2

Code in C


#include <stdio.h>

int main(){
	//variables
	int x, n, p, q, m;
	
	//input
	printf("Enter x and n: ");
	scanf("%d%d", &x, &n);
	
	//mod
	q = x / n;	//finding quotient (integer part only)
	p = q * n;	//finding product
	m = x - p;	//finding modulus
	
	//output
	printf("Modulus: %d\n", m);
	return 0;
}

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT