Since code-efficiency was one of the tags, modify the answers a bit:
while ((n%d) && (d<n/d)) d+=2;
The compiler is more likely to reuse the result of the division operator in this way.
Considering the compiler output for gcc -O3 in the version of the loop that I propose, there is only one separation operation per iteration, and the result is used for both comparisons:
L18: cmpl %esi, %ecx jle L13 movl %ebx, %eax addl $2, %esi cltd idivl %esi testl %edx, %edx movl %eax, %ecx jne L18 .p2align 4,,15 L13:
While version while ((n%d) && d*d < n) d+=2; gives:
L8: movl %ecx, %eax imull %ecx, %eax cmpl %ebx, %eax jge L3 movl %ebx, %eax addl $2, %ecx cltd idivl %ecx testl %edx, %edx jne L8 .p2align 4,,15 L3:
And it is clear that it performs both multiplication and division by each iteration.
source share