Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# efficient remainder

manolis tsamis
Greenhorn
Posts: 4
Hallo! Is there any way to find fast if a division has remainder or not. I don't want to know the remainder, just if there is. Thanks in advance.

Henry Wong
author
Marshal
Posts: 21745
85
manolis tsamis wrote:Hallo! Is there any way to find fast if a division has remainder or not. I don't want to know the remainder, just if there is. Thanks in advance.

Henry

manolis tsamis
Greenhorn
Posts: 4
I am currently using that but because it's repeated million times modulus is slowing it down... I was searching for another thing to do

William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
Checking the java virtual machine book we see that there are opcodes irem and lrem to get the remainder for int and long division respectively.

I don't think you are going to get faster than a single opcode.

Bill

Henry Wong
author
Marshal
Posts: 21745
85
William Brogden wrote:Checking the java virtual machine book we see that there are opcodes irem and lrem to get the remainder for int and long division respectively.

I don't think you are going to get faster than a single opcode.

... unless the OP can figure out a new algorithm that doesn't need to do the operator millions of times.

Henry

Winston Gutkowski
Bartender
Posts: 10527
64
manolis tsamis wrote:I am currently using that but because it's repeated million times modulus is slowing it down... I was searching for another thing to do

Are you absolutely sure that it's the modulus that's slowing you down? Most attempts at efficiency end up focusing on the wrong thing, so you'd better be able to prove that its the '%' that's causing all your problems before you start looking for a "better %".

That said, there are faster ways of doing it, the most basic being if d (your divisor) is a power of two:
x % d == x & (d-1)

but you'd better be awfully sure it's going to help before you start littering your program with arcane crap like that.

Winston