473,788 Members | 2,784 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Quickest way for even numbers

Hi all!
I want to check whether a number is odd or even. I've made an algorithm
but I believe there should be a faster one ( maybe a macro ).
Here it goes :

int iseven ( int number )
{
int first;
int tempnum;

tempnum = number;

first = number >> 1;
number = first << 1;

if ( tempnum == number )
return 0;

return 1;
}
Thanks in advance
Nov 14 '05 #1
15 4292
Darksun4 <da*******@yaho o.gr> wrote:
I want to check whether a number is odd or even. I've made an algorithm
but I believe there should be a faster one ( maybe a macro ).
Here it goes :

int iseven ( int number )
{ return !(number % 2); }


Alternatively: return (number & 1)^1

Ciao Chriss
Nov 14 '05 #2
Darksun4 a exprimé avec précision :
I want to check whether a number is odd or even. I've made an algorithm
but I believe there should be a faster one ( maybe a macro ).
Here it goes :

int iseven ( int number )
Identifiers beginning with is followed by lowercases are reserved for
future language extensions.

is_even() is fine (and additionally, readable).
{
int first;
int tempnum;

tempnum = number;

first = number >> 1;
Bitwise operators only work portably with unsigned integers.
number = first << 1;
DOn't shift anything if you want to go fast.
if ( tempnum == number )
return 0;

return 1;
}
Thanks in advance

What about

int is_even (long number)
{
return ((unsigned long) number & 0x1ul) == 0:
}

or

inline int is_even (long long number)
{
return (number & 0x1ull) == 0:
}

if you have C99.

Also consider an unsigned version of the functions

int is_even_ul (unsigned long number)

etc.

--
Emmanuel

Nov 14 '05 #3
Emmanuel Delahaye avait prétendu :
inline int is_even (long long number)
{
return (number & 0x1ull) == 0:
return ((unsigned long long) number & 0x1ull) == 0:
}


--
Emmanuel

Nov 14 '05 #4
Darksun4 <da*******@yaho o.gr> spoke thus:
I want to check whether a number is odd or even. I've made an algorithm
but I believe there should be a faster one ( maybe a macro ).
I suspect that you're not gaining much performance advantage over

!(number%2)

at the expense of quite a bit of clarity (IMHO). The overhead of the
function call probably more than offsets the possible penalty of using
the modulo operator.
int iseven ( int number )
{
int first;
int tempnum; tempnum = number; first = number >> 1;
If number happens to be negative, the results of this shift operation
are implmentation-defined.
number = first << 1; if ( tempnum == number )
return 0; return 1;
}


--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #5
Emmanuel Delahaye <em***@yourbran oos.fr> spoke thus:
Bitwise operators only work portably with unsigned integers.


According to my reading of K&R2, the result is also portable for
signed integers with positive values.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #6
Emmanuel Delahaye wrote:
Darksun4 a exprimé avec précision :
I want to check whether a number is odd or even. [...]



What about

int is_even (long number)
{
return ((unsigned long) number & 0x1ul) == 0:
}

or

inline int is_even (long long number)
{
return (number & 0x1ull) == 0:
}

if you have C99.


"Premature optimization is the root of all evil," but
why not

inline int is_even(long long number) {
return ((unsigned int /* yes, int */) number & 1u) == 0;
}

... on the assumption that operations on `int'-sized data
may well be faster than on wider types.

--
Er*********@sun .com

Nov 14 '05 #7
In <40************ **@sun.com> Eric Sosman <Er*********@su n.com> writes:
Emmanuel Delahaye wrote:
Darksun4 a exprim=E9 avec pr=E9cision :
=20
I want to check whether a number is odd or even. [...]

=20
=20
What about
=20
int is_even (long number)
{
return ((unsigned long) number & 0x1ul) =3D=3D 0:
}
=20
or
=20
inline int is_even (long long number)
{
return (number & 0x1ull) =3D=3D 0:
}
=20
if you have C99.


"Premature optimization is the root of all evil," but
why not

inline int is_even(long long number) {
return ((unsigned int /* yes, int */) number & 1u) =3D=3D 0;
}

=2E.. on the assumption that operations on `int'-sized data
may well be faster than on wider types.


Both are going to be unnecessarily slow on machines using
sign-magnitude, where the conversion from negative values to unsigned
values is actually changing representation. Unless the compiler is
smart enough to figure out the obfuscated intent, of course.

How about "return number % 2 == 0"; and letting the compiler choose the
best machine code sequence? We're no longer in the dark seventies, when
compilers had to fit into 64 KB and run on pathetically slow hardware...

The code generated from my version by gcc on x86, for a long int
parameter, is:

xorl %eax, %eax
testb $1, 4(%esp)
sete %al
ret

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #8
Emmanuel Delahaye <em***@YOURBRAn oos.fr> wrote:
Emmanuel Delahaye avait prétendu :
inline int is_even (long long number)
{
return (number & 0x1ull) == 0:


return ((unsigned long long) number & 0x1ull) == 0:
}


Why would you do that? Since one operand of the '&' is unsigned
long long, the other will be promoted to it without a cast.

More readable, would be:

return (number & 1) == 0;

or !(number & 1) if you prefer, as then the 1 (1 decimal = 1 hex)
will be promoted to match 'number'. I would even go for
'int' instead of 'long long' since I don't care about any
bits other than the least-significant one.
Nov 14 '05 #9
Da*****@cern.ch (Dan Pop) wrote in news:cd******** **@sunnews.cern .ch:
The code generated from my version by gcc on x86, for a long int
parameter, is:

xorl %eax, %eax
testb $1, 4(%esp)
sete %al
ret


Pretty tight, with return (number % 2) == 0 I get

srawi r0,r3,1
addze r0,r0
mulli r0,r0,2
subf r12,r0,r3
cntlzw r3,r12
rlwinm r3,r3,27,5,31
blr

and with return (number & 1U) == 0;
rlwinm r12,r3,0,31,31
cntlzw r3,r12
rlwinm r3,r3,27,5,31
blr

with Diab 5.0.3. I guess Diab's not as smart as it could be. The var.
'number' is in r3 of course.

--
- Mark ->
--
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4136
by: me | last post by:
Hi guys - the question is in the subject line. I thought of one quick way: std::ifstream input("myfile.dat") ; std::istreambuf_iterator beg(input), end ; std::vector DataFile(beg,end) ;
4
1676
by: puzzlecracker | last post by:
I am using cpp by the way? Thanks
6
1552
by: Deano | last post by:
I think my brain has short-circuited again :) Is this the quickest way to check for the existence of a given value in an array? e.g For i = 0 To rrst.RecordCount If myArray(i) = DLookup("ID", "tblmain", "Salary = " & varSomeValue) Then
0
1020
by: N k via DotNetMonster.com | last post by:
What is the quickest way to find the index of the first letter in a richTextBox? -- Message posted via http://www.dotnetmonster.com
6
8961
by: Jozef Jarosciak | last post by:
Quickest way to find the string in 1 dimensional string array! I have a queue 1 dimensional array of strings called 'queue' and I need a fast way to search it. Once there is match, I don't need to search any longer. Currently I am using this code. But I think it's too slow, because it runs through whole dimension. I know this is trivial question, but is there any way to stop this loop, or better way to search? I mean - FASTER?
2
1412
by: Emmanuel | last post by:
Hi there, My client would like to process an xml file. the structure of which is as below. <xml> <stockitem> <releaseddate>.....date value...</releaseddate> <...aditional tags for additional info> </stockitem> <stockitem>
17
4628
by: Ron | last post by:
I want to write a program that will accept a number in a textbox for example 23578 and then in a label will display the sum of the odd and even number like this... the textbox containsthe number 23578 the label would say: Sumof odd number is: 15 Sum of even number is: 10 any ideas?
30
29689
by: bdsatish | last post by:
The built-in function round( ) will always "round up", that is 1.5 is rounded to 2.0 and 2.5 is rounded to 3.0. If I want to round to the nearest even, that is my_round(1.5) = 2 # As expected my_round(2.5) = 2 # Not 3, which is an odd num I'm interested in rounding numbers of the form "x.5" depending upon whether x is odd or even. Any idea about how to implement it ?
18
4914
by: =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?= | last post by:
Hello. It seems a year is all it takes for one's proficiency in C++ to become too rusty. Professionally, I've been away from the language (and from programming in general), but I still preserve an appreciation for it. So I decided to toy with some idea, just for fun and for evaluating how rusty I'd become. "Let me write a simple functor for sorting the elements of a collection! I will start with a simple collection of integers.", I...
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8995
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5403
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.