Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way, in C, to see if a number is divisible by another?

Which is the best way, in C, to see if a number is divisible by another? I use this:

if (!(a % x)) {
// this will be executed if a is divisible by x
}

Is there anyway which is faster? I know that doing, i.e, 130 % 13 will result into doing 130 / 13 per 10 times. So there are 10 cycles when just one is needed (I just want to know if 130 is divisible by 13).

Thanks!

like image 573
Joseph Avatar asked Nov 27 '22 22:11

Joseph


1 Answers

I know that doing, i.e, 130 % 13 will result into doing 130 / 13 per 10 times

Balderdash. % does no such thing on any processor I've ever used. It does 130/13 once, and returns the remainder.

Use %. If your application runs too slowly, profile it and fix whatever is too slow.

like image 152
Robᵩ Avatar answered Dec 15 '22 03:12

Robᵩ