Objective: 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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FindRemainder { | |
public static void remainder(int n, int divisor){ | |
if(divisor==0){ | |
System.out.println("Cannot divide by 0"); | |
return; | |
} | |
//if either number or divisor is negative | |
if(n<0) | |
n *=–1; | |
if(divisor<0) | |
divisor *= –1; | |
int number = n; | |
//subtract divisor from n till n>=divisor | |
while(n>=divisor){ | |
n -= divisor; | |
} | |
System.out.println("Number: " + number + " , divisor: " + divisor + ". remainder: " + n); | |
} | |
public static void main(String[] args) { | |
int n = 10; | |
int divisor = 4; | |
remainder(n, divisor); | |
} | |
} |
Output:
Number: 10, divisor: 4. remainder: 2
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;