How do I check if an integer is even or odd?
Use the modulo (%) operator to check if there's a remainder when dividing by 2:
if (x % 2) { /* x is odd */ }
A few people have criticized my answer above stating that using x & 1 is "faster" or "more efficient". I do not believe this to be the case.
Out of curiosity, I created two trivial test case programs:
/* modulo.c */
#include <stdio.h>
int main(void)
{
int x;
for (x = 0; x < 10; x++)
if (x % 2)
printf("%d is odd\n", x);
return 0;
}
/* and.c */
#include <stdio.h>
int main(void)
{
int x;
for (x = 0; x < 10; x++)
if (x & 1)
printf("%d is odd\n", x);
return 0;
}
I then compiled these with gcc 4.1.3 on one of my machines 5 different times:
- With no optimization flags.
- With -O
- With -Os
- With -O2
- With -O3
I examined the assembly output of each compile (using gcc -S) and found that in each case, the output for and.c and modulo.c were identical (they both used the andl $1, %eax instruction). I doubt this is a "new" feature, and I suspect it dates back to ancient versions. I also doubt any modern (made in the past 20 years) non-arcane compiler, commercial or open source, lacks such optimization. I would test on other compilers, but I don't have any available at the moment.
If anyone else would care to test other compilers and/or platform targets, and gets a different result, I'd be very interested to know.
Finally, the modulo version is guaranteed by the standard to work whether the integer is positive, negative or zero, regardless of the implementation's representation of signed integers. The bitwise-and version is not. Yes, I realise two's complement is somewhat ubiquitous, so this is not really an issue.
Test if number is odd or even
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
Check if a number is odd or even in Python
if num % 2 == 0:
pass # Even
else:
pass # Odd
The %
sign is like division only it checks for the remainder, so if the number divided by 2
has a remainder of 0
it's even otherwise odd.
Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:
if num % 2:
pass # Odd
else:
pass # Even
How to determine if a number is odd in JavaScript
Use the below code:
function isOdd(num) { return num % 2;}console.log("1 is " + isOdd(1));console.log("2 is " + isOdd(2));console.log("3 is " + isOdd(3));console.log("4 is " + isOdd(4));
Testing if a high number is odd or even in C
The problem is not in the modulo operation, but in the type of data you are using.
Your id number is an int
, which is (in this case) formed with 32 bits. This means that the maximum number you can use is 2,147,483,647
, and you are using a bigger number.
You should try using long
, or a number type that uses more than 32 bits, like long long
. This means that the maximum number you can use is 263 - 1 = 9,223,372,036,854,775,807
, solving your problem.
So, you should make these changes in your code:
long long id;
printf("Enter the Id: ");
scanf("%lld", &id);
This Page provides a good explanation of the types available in C++.
Testing whether a value is odd or even
Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven
and isOdd
functions, so you don't have to duplicate error handling in both functions.
Trying to test if an input is odd or even
You'd better simplify all of this, you don't need to call your method multiple times :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (writeAndCheckEven(Integer.parseInt(scanner.nextLine()))) {
System.out.println("You added an even number, go on");
}
System.out.println("You added an odd number, done!");
}
private static boolean writeAndCheckEven(int number) {
return number % 2 == 0;
}
- you don't need to use a
return
if there is no more code after - you can directly use the
scanner
in the parameter - don't use both
while
andif
it won't do what you want
how TEST instruction check if number is EVEN or ODD in assembly language
I think i understand it now, that how can test be used to find out if number is even or odd!!!
You just have to check the least significant bit of the number,
example:
1001 is odd,
1110 is even
I want to check if 101 is even or odd
then i'll do this:
mov al,101b
test al,1b
by doing this,
test will perform and operation between 101 and 001
so only the least bit would be checked and if it is '1' then number is odd otherwise even
then finally we can use jump to print if number is even or not:
je ; if number is even
How to check if a number is odd or even in little man computer
The infinite loop occurs at BRP ODD
. Be aware that BRP
also branches when the accumulator is zero. So it is a "branch when not negative" instruction. And when the execution continues at ODD
, it falls through to EVEN
, which makes the code at ODD
irrelevant. At EVEN
the accumulator is loaded with zero, and so the BRP
will branch again... infinitely.
There is also a missing check for 0: when the input is zero, you should not perform the subtraction at all.
Not a problem, but having a reference to mailbox 60 can be better replaced with a reference to a label, like ZERO
.
The code includes logic that really isn't necessary:
You have included code to calculate the quotient, since the code adds ONE
to the RESULT
every time you subtract the DIVISOR
from the NUMBER
. However, that RESULT
is finally overwritten with either ONE
or zero (address 60), so that quotient was calculated for nothing. As you only want to output whether the input was odd or even, you should drop the quotient calculation from your code.
Also avoid code repetition. You currently perform the SUB
at two different places. This should not be necessary as the logic should be the same in both instances.
Here is the code reduced to its basics:
#input: 11
INP
STA NUMBER
LOOP BRZ OUTPUT # remainder is zero! so output a zero
SUB DIVISOR
BRP LOOP
LDA ONE # when result is negative, input was odd
OUTPUT OUT
HLT
NUMBER DAT
DIVISOR DAT 2
ONE DAT 1
ZERO DAT 0
<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>
Related Topics
Error Message Strict Standards: Non-Static Method Should Not Be Called Statically in PHP
How to Remove Array Element and Then Re-index Array
MySQL: Select Random Entry, But Weight Towards Certain Entries
Woocommerce: Which Hook to Replace Deprecated "Woocommerce_Add_Order_Item_Meta"
Are There Good Tutorials on How to Use Pdo
Reference - Composer Error "Your PHP Version Does Not Satisfy Requirements" After Upgrading PHP
Override Method Parameter With Child Interface as a New Parameter
How Can Strip Whitespaces in PHP'S Variable
PHP: How to Remove Specific Element from an Array
Constant Filter_Sanitize_String Is Deprecated
How to Loop Through a MySQL Result Set More Than Once Using the MySQL_* Functions
Implementing Condition in Xpath
How to Change Public Folder to Public_Html in Laravel 5