# How to find remainder without % operator?

·3 mins
Problem Solving
Author
Mayukh Datta

We use %, which is called the modulo or remainder operator, in any program when we want to find the remainder of a number divided by another number. The operation carried out is known as the modulo operation (in short, we call it mod). It is a very fundamental operation in Computer Science and is used in solving many different problems. I guess you’ve already used it in solving basic problems like finding HCF using Euclid’s algorithm, to reverse an integer, and many more.

C code to find a mod b (where a and b are integers) using % operators:

#include<stdio.h>
int main(void){
int a, b;
printf("Enter a & b: ");
scanf("%d %d", &a, &b);
printf("%d mod %d = %d", a, b, a%b);
return 0;
}


This program works only for integer inputs. If we want to find a mod b (where a and b are real numbers), then what?

Unlike Python, in C language % operator doesn’t support float or double operands. Therefore, one has to take another route. We will take the other route a little later. But first let’s try to carry out the modulo operation for integer inputs without using the % operator.

We know that quotient(q) is what we get after we divide a dividend(a) by a divisor(b) and the leftover of the division is called the remainder(r). If both the divisor and the quotient are factors of the dividend then we get remainder zero otherwise we get something as the remainder.

In nearly all computing systems, the quotient and the remainder of dividend divided by the divisor satisfy

$q \in Z\\ a = bq + r\\ |r| < |b|$

Therefore, we can derive the equation needed to find the remainder.

$r = a - bq$

C code to find remainder without using % operator:

#include<stdio.h>
int main(void){
int a, b, r, q;
printf("Enter a & b: ");
scanf("%d %d", &a, &b);
//q is a member of set Z i.e Integers
q = a / b;
r = a - (b\*q);
printf("%d mod %d = %d", a, b, r);
return 0;
}


Let’s go back to how to find the remainder when inputs are real numbers. The above program can be used to do so. We need to take double or float variables instead of integer variables (except for the q).

C code:

#include<stdio.h>
int main(void){
double a, b, r;
int q;
printf("Enter a & b: ");
scanf("%lf %lf", &a, &b);
//q is a member of set Z i.e Integers
q = a / b;
r = a - (b\*q);
printf("%g mod %g = %g", a, b, r);
return 0;
}


In C++, we can simply do it by using the fmod() function. Below is the implementation:

#include<iostream>
#include<cmath>
using namespace std;
int main(void){
double a, b;
cout<<"Enter a & b: ";
cin>>a>>b;
printf("%g mod %g = %g", a, b, fmod(a, b));
return 0;
}