Jump to content

Modular Arithmetic

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
knightry

knightry

    Newbie

  • Members
  • Pip
  • 2 posts
Hi all, long time reader, first time poster

Let me preface this with saying I am asking this question from the standpoint of a competitive programmer (competitions like TopCoder and ACM ICPC).

My question is this: does anyone know how Java implements mod? Specifically, if you type in a%b, does java simply interpret this as a-(a/b)*b, or does it do something more efficient?

I've done some problems recently in which mod has been called *a lot* of times, and am looking for ways to make the calls more efficient.

Thanks,
Stephen

#2
knightry

knightry

    Newbie

  • Members
  • Pip
  • 2 posts
So, nobody has any idea?

#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Well, since Java is open-source, you could look at the code, but it probably depends on the individual processor. If the CPU implements mod, why "implement" it in Java?
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#4
PythonPower

PythonPower

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 230 posts

WingedPanther said:

Well, since Java is open-source, you could look at the code, but it probably depends on the individual processor. If the CPU implements mod, why "implement" it in Java?

Since Java needs to be compatible across all platforms, I have heard implementations of the JRE sometimes don't rely on the processor, directly, for calculations. I believe this only applies to floating point calculations, however.

You seek r where a = r (mod n). Most likely used if hardware cannot is, as you guessed, r = a - n floor(a/n). However, if n = 2k then r = and(a, n-1). Do you know anything about a or n?