Program to find remainder without using modulo or % operator in C++



In this problem, we are given two numbers, N and D. Our task is to create a Program to find remainder without using modulo or % operator in C++.

Problem description − We need to find the remainder that will be left after dividing the number N by D. But we cannot use the modulo or % operator for this.

Let’s take an example to understand the problem

Input

N = 53 D = 3

Output

2

Solution Approach

To find the remainder, a simple approach is to find the number less than N which is the multiple of D. And the substrate the number from N. To return the remainder.

Program to illustrate the working of our solution

Example

 Live Demo

#include <iostream> using namespace std; int findRem(int N, int D) {    int i ;    for(i = 0; ;i++) {       if(D * i >= N)          break;    }    return N - (D * (i-1)); } int main(){    int N = 45, D = 6 ;    cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);    return 0; }

Output

The remainder after dividing 45 by 6 is 3

Another solution is by using the integer value of the quotient of the dividing which can be extracted directly by initializing it to an int value in C++. Then multiplying it with D. And subtracting the value from N gives the remainder.

Program to illustrate the working our solution

Example

 Live Demo

#include <iostream> using namespace std; int findRem(int N, int D) {    int Q = N/D;    int R = N - (D * Q);    return R; } int main(){    int N = 45, D = 6 ;    cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);    return 0; }

Output

The remainder after dividing 45 by 6 is 3
Updated on: 2020-09-17T05:03:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements