How to find the remainder of dividing two numbers without using the modulo operator!! My teacher gave me this exact exercise and It\'s only my 5th lecture in a course calle
Well, you could do what the modulo operator typically does internally.
Inside a loop, substract b
from a
repeatedly. When this is no longer possible, the number you're left with is your answer.
Here's a code example. If you're trying to accomplish this for decimal numbers, be mindful of rounding errors for floating-point values.
double result = a;
while(result - b >= 0) {
result -= b;
}
return result;
Note that if you're working with integers, and you're allowed to use the division operator, you don't need to use a loop.
However, do keep in mind that all that division does is repeated subtraction. If this is for pedagogical purposes, I think it's cooler to do it my way.
When using double
s, that equation will always return 0
. When using int
that equation must work because of truncation (integer division).
Here is the algorithm to compute the remainder in a division. Let's say you want to find a % b
:
while dividend is larger or equal than divisor
substract divisor from dividend
print last result
Implemented in Java it will look like:
public static void main(String[] args)
{
double a = 5, b = 2;
while (a >= b) {
a -= b;
}
System.out.println(a);
}
You need to take the Math.floor of a/b.
you have a%b = a - (a/b)*b but really a%b= a- (Math.floor(a/b)*b)
This is because without the math.floor it includes the decimal remainder and (a/b)*b is equal to a so when you subtract it from a you will get 0 every time, just as you experienced.
I've just tried this
public static void main (String [] args){
int a = 50;
int b = 9;
int c = a%b;
int d = a - (a/b)*b;
System.out.println(c);
System.out.println(d);
}
And it seems to work. What types are your variables?
It makes no sense to perform %
on double
or float
numbers, because floating point numbers actually each represent a very small range of values, rather than an exact value. Often, the internal representation of a floating point number isn't the same number in that range as the actual decimal that you used to create the number. This means that the result of %
is formally undefined, for floating point types.
If you try 0.3 % 0.1
in Java, you actually get 0.09999999999999998
, which seems at first sight to be incorrect; but this makes as much sense as any other result, given what floating point numbers really represent.
Here is the simplest solution for working out %
, without actually using %
.
a - b * (long)(a/b);
It will perform better than an answer that does repeated subtraction, because it doesn't have to loop over and over.
But this solution inevitably falls victim to the same trap as certain other answers on this page, namely that the "correct" answer is formally undefined.
This solution will also give overflow problems if your numbers are extremely large.