Can anyone explain a formula for determining odd and even numbers in loops. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
- 1

Can anyone explain a formula for determining odd and even numbers in loops.

Specifically I want to omit a user input in the loop if the number is odd.

22nd Dec 2021, 8:06 PM
Robert Britton
Robert Britton - avatar
2 ответов
+ 1
A much faster test than using modulo is to check the number's lowest bit. If the bit is 1, the number is odd. If it is 0, the number is even. You can do this by using the bitwise & (and) operator. if (num&1==1) //odd if (num&1==0) //even
23rd Dec 2021, 3:15 AM
Brian
Brian - avatar
+ 8
You need to use modulus (%) operator, if num%2==0 number is even, if not it's an odd number. So you could use while loop, or for in if you are working with arrays, for of if you are working with objects
22nd Dec 2021, 8:09 PM
Brigi
Brigi - avatar