Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find remainder without using modulo operator

Objec­tive:  Write Given two inte­gers ‘num­ber’ and ‘divi­sor’, Write an algo­rithm to find the remain­der if ‘num­ber’ is divided by ‘divisor’.

Con­di­tion: You are not allowed to use mod­ulo or % operator.

Exam­ple:

num = 10, divisor = 4
remainder = 2

num = 11, divisor = 2
remainder = 1

This is fun puz­zle which is asked in the interview.

Approach:

1.     This prob­lem will become very triv­ial if use of mod­ulo or % oper­a­tor is allowed.

2.     Idea is Keep sub­tract­ing the divi­sor from num­ber till number>=divisor.

3.     Once the step above is done, remain­ing value of num­ber will be the remainder.

Exam­ple:

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

Code:

Out­put:

Number: 10, divisor: 4. remainder: 2

You may also like...