Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Odd numbers

Status
Not open for further replies.

Flagada

Programmer
Joined
Dec 22, 2005
Messages
8
Location
NL
Hi,

This might be a stupid question: How do I check if an integer value is odd?

Thanks.
 
[tt]
int n=123;
if(n/2*2!=n)
printf("odd");
[/tt]
 
Silly me, I forgot the % operator:
[tt]
int n=123;
if(n%2)
printf("odd");
[/tt]
 

Okay thanks, it solved my problem.

So if I get it right, n%2 means that n cannot be didived by 2 ? And does n%3 then means that n cannot be divided by 3 ?

Or am I wrong?

Bill
 
n%m means n modulo m (abbreviated n mod m)
n%2 means n modulo 2
n%3 means n modulo 3

The modulo is simply the remainder, so if the modulo is 0, the number n is exactly divisible by m. If n is not divisible by m, then there is a remainder.

Hence, (6%2) equals 0, (5%2) equals 1, (5%3) equals 2 etc. To clarify the example above by TonyGroves:

Code:
int n=123;
if (n%2)  // literally means if (n%2 != 0)
  printf ("odd");

Hope that helps to clarify.
 

Ok, now i got it. Thanks.

Bill
 
As it is a question of integers it's equally usefull to simply do a "AND" with 0x01.

if(n & 1) /* Do the odd thing */;
else /* Do the even thing */;

It's faster than '%' as it requires no division.

Totte
Keep making it perfect and it will end up broken.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top