How to find remainder without % operator?


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 pretty basic problems like finding HCF using Euclid's algorithm, to reverse an integer and many more.

Below is a program in C to find a mod b (where a and b are integers) using % operator:
#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 one wants 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\]



Below is the program in C 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;
}
A little earlier we were talking about another way that would help us to find remainder when a and b are real numbers. The above program can be used to do so. We just need to take double or float variables instead of integer variables (except for the q). Below is the 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 could simply do this 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;
}
Happy programming!

If you've found any errors or want to give a feedback then comment below.


Comments