Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

efficient remainder

 
manolis tsamis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21510
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


How about the modulus operator?

Henry
 
manolis tsamis
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21510
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic