Find remainder without using modulo operator

Objec­tive:  Write Given two integers ‘number’ and ‘divisor’, Write an algorithm to find the remainder if ‘number’ is divided by ‘divisor’.

Condition: You are not allowed to use modulo or % operator.

Example:

num = 10, divisor = 4
remainder = 2

num = 11, divisor = 2
remainder = 1

This is fun puzzle which is asked in the interview.

Approach:

1.     This problem will become very trivial if use of modulo or % operator is allowed.

2.     Idea is Keep subtracting the divisor from number till number>=divisor.

3.     Once the step above is done, remaining value of number will be the remainder.

Example:

number = 10, divisor = 4
number = number – divisor => 10 – 4 = 6
number = number – divisor => 6 – 4 = 2
remainder = 2

Code:

Output:

Number: 10, divisor: 4. remainder: 2

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

  • ashot madatyan

    Continuously subtracting is not such an effective way to go. Instead, we can do it like this:
    mul = int(number/divisor);
    remainder = number – mul * divisor;

%d bloggers like this: