A
A
askogorev2013-11-28 17:24:46
C++ / C#
askogorev, 2013-11-28 17:24:46

Which is faster: n%2 or n&1 (c++)?

For the sake of interest: what will work faster? Conjunction n&1or remainder of division n%2?
For example:

int n = 72341;
if (n%2)
{
  // ...
}

PS:int N;

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikita Gusakov, 2013-11-28
@hell0w0rd

equally. Write in a way that is understandable, compilers optimize better than you

L
Lolshto, 2013-11-28
@Lol4t0

You can also try to force the compiler to use division instead of conjunction. Clang is still possible, but gcc refuses even with completely disabled optimization.

int main(int n, char**)
{
  if (n%2)
  {
    return 1;
  };
}

main:
  push	rbp
  mov	rbp, rsp
  mov	DWORD PTR [rbp-4], edi
  mov	QWORD PTR [rbp-16], rsi
  mov	eax, DWORD PTR [rbp-4]
  and	eax, 1
  test	eax, eax
  je	.L2
  mov	eax, 1
  jmp	.L3
.L2:
  mov	eax, 0
.L3:
  pop	rbp
  ret

M
Masterme, 2013-11-28
@Masterme

at a low level - conjunction

T
TheRipper, 2013-11-28
@TheRipper


There is also a %) option
, although I suspect that I don’t have the right way to count the number of bits here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question