What is the difference between minus and mod operators in terms of time required for computation? I have noticed that mod takes significantly lesser time than minus. For example -
Problem statement - I'm incrementing a variable 'x' by 1, 'x' should not be greater than 'y'. This can be done in 2 ways.
1)
if(x > y) x = x - y;
or
2)
if(x > y) x = x % y;
The 2nd approach is faster than 1st. Can anyone please explain?
Here's the code - init, y and hop are inputs, hop is always less than y.
int x = init;
int count = 1;
do{
x += hop;
count++;
if (x > y)
x = x - y;
} while(x != y);
P.S. The code is just an example. I'm not concerned about what it does. I just want to know how using % instead of - reduces the time.