division operation query..!

which operation is faster…? (a & b are int type) ,each operation is performed 10^9 times…!

  1. (a/b)
  2. (a%b)
1 Like

I have written a JAVA code to test this, as I also was very curious that which one is faster.

class Faster
    public static void main(String args[])
        long x=10,y=1;
        long a1=System.nanoTime();
        for(long i=1;i<=10000;i++)
        long a2=System.nanoTime();
        System.out.println("Time taken for division is "+(a2-a1)+" nanoseconds");
        long t;
        for(long i=1;i<=10000;i++)
        System.out.println("Time taken for modulus is  "+(a2-a1)+" nanoseconds");

I was shocked to see the results. I thought modulus operatio will take lesser time. but see the results( from Console )

Modulus is slower than Division

Here is the link Link to the Program. If you run this link, it will show that the Division is much much much more faster than Modulus operation!

I think this would have helped you. :slight_smile:

It’s kinda obvious that % will be at least not faster than /. And both of them are really slow.

Unless you have some special case, like dividing by power of 2, there is no fast way to calculate a/b.

And there is no way to calculate % fast - there is nothing significantly better than calculating it using followin logic: a%b=a-(a/b)*b.

Usually % should work with same speed as /. Generally CPUs return both quotient and remainder :slight_smile:

I have no idea how things work in Java, but for C++ such testing would look at least funny :slight_smile:

After rewriting this code to C++ and using properly configured compiler… You have cold calculations here, therefore everything will be ignored, except last / operation and last operation, and they will be optimized by bitwise operations (because you are dividing by power of 2). That makes it really funny - code to test and / does 0 % and / operations :slight_smile:

No offence - I have no idea about Java things, probably your code is OK :slight_smile: Just a funny observation from C++ user.

no brother, JAVA is likely as CPP :slight_smile: you are also right, I should have used Bitwise Shift operations. Thanks :slight_smile:

Division is faster than modulo. Use Euclid algorithm to find modulo using division.