473,405 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Integer div and mod together?

Hi,

I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both
values in one shot? It seems quite wasteful in time to do the division
twice in order to get both of those values, when it would be quite easy to
return them both from a single function.

I saw someone's code implementing a divmod() function using assembler.
But it doesn't look like there is a built-in function for doing that in C++,
correct? Seeing as how I do a lot of mathematical calculations, I'm
thinking of writing one myself, but writing one in assembler is
platform-specific, and writing one in C++ doesn't seem logical. It seems to
me that it ought to part of the C++ standard, and implemented by compiler
vendors to target the specific platform(s) they support.

Any thoughts? (Or perhaps I should take this to comp.std.c++?)

-Howard

Jul 22 '05 #1
13 27343
* Howard:
I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both
values in one shot? It seems quite wasteful in time to do the division
twice in order to get both of those values, when it would be quite easy to
return them both from a single function.

I saw someone's code implementing a divmod() function using assembler.
But it doesn't look like there is a built-in function for doing that in C++,
correct? Seeing as how I do a lot of mathematical calculations, I'm
thinking of writing one myself, but writing one in assembler is
platform-specific, and writing one in C++ doesn't seem logical. It seems to
me that it ought to part of the C++ standard, and implemented by compiler
vendors to target the specific platform(s) they support.

Any thoughts? (Or perhaps I should take this to comp.std.c++?)


Measure before you optimize.

You might be surprized.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2
Howard wrote:
I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both
values in one shot? It seems quite wasteful in time to do the division
twice in order to get both of those values, when it would be quite easy to
return them both from a single function.
You might try doing it in two consecutive statements and see if the
compiler manages to optimise them properly.
I saw someone's code implementing a divmod() function using assembler.
But it doesn't look like there is a built-in function for doing that in C++,
correct? Seeing as how I do a lot of mathematical calculations, I'm
thinking of writing one myself, but writing one in assembler is
platform-specific,
And why is *that* stopping you? The Standard library, for example, is all
platform- and implementation-specific. No big deal. Just do it on every
platform where you need it.
and writing one in C++ doesn't seem logical. It seems to
me that it ought to part of the C++ standard, and implemented by compiler
vendors to target the specific platform(s) they support.

Any thoughts? (Or perhaps I should take this to comp.std.c++?)


If you propose to have such function added, I'd rather to to 'comp.std.c'.
But I am not sure all CPUs can do that, although IIRC, all I every wrote
an assembly program for, did.

There are three incarnations of 'remquo' functions in C99, but they are
for floating point numbers.

V
Jul 22 '05 #3
Howard wrote:
Hi,

I know I can do integer division with the / operator, and get the modulus with the % operator, but is there any function that calculates both values in one shot?


The div function does both, but it's not (even close to) guaranteed
that it'll be any more efficient than using / and %.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 22 '05 #4
Howard wrote:
I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both
values in one shot?
Yes. It is called 'div' ('ldiv'). It is inherited from C standard
library. However, how exactly it calculates these values depends on the
concrete implementation.
It seems quite wasteful in time to do the division
twice in order to get both of those values, when it would be quite easy to
return them both from a single function.
Firstly, just because you write the division twice in your C++ code
doesn't mean that it will be performed twice in the compiled code. A
smart compiler can easily optimize away the extra division.

Secondly, a dedicated function might introduce extra overhead that will
defeat all the benefits (this applies to the aforementioned 'div'/'ldiv'
functions as well). Meanwhile, if the compiler is smart enough to
perform low-overhead inlining of such functions, then it is probably
smart enough to perform the optimization mentioned under "firstly".
I saw someone's code implementing a divmod() function using assembler.
But it doesn't look like there is a built-in function for doing that in C++,
correct?


There's a C library function (see above). Does this qualify as
"built-in" in your book?

--
Best regards,
Andrey Tarasevich
Jul 22 '05 #5
Howard wrote:
I know [that] I can do integer division with operator/
and get the [remainder] with operator%
but is there any function that calculates both values in one shot?

It seems quite wasteful in time to do the division twice
in order to get both of those values
when it would be quite easy to return them both from a single function.

I saw someone's code implementing a divmod() function using assembler.
But it doesn't look like there is a built-in function for doing that in C++,
correct? Seeing as how I do a lot of mathematical calculations,
I'm thinking of writing one myself
but writing one in assembler is platform-specific
and writing one in C++ doesn't seem logical.
It seems to me that it ought to part of the C++ standard
and implemented by compiler vendors
to target the specific platform(s) they support.


DIV(3) Linux Programmer’s Manual DIV(3)
NAME
div, ldiv, lldiv, imaxdiv -
compute quotient and remainder of an integer division
SYNOPSIS
#include <stdlib.h>
div_t div(int numerator, int denominator);
ldiv_t ldiv(long numerator, long denominator);
lldiv_t lldiv(long long numerator, long long denominator);
#include <inttypes.h>
imaxdiv_t imaxdiv(intmax_t numerator, intmax_t denominator);
DESCRIPTION
The div() function computes the value numerator/denominator and
returns the quotient and remainder in a structure named div_t
that contains two integer members (in unspecified order)
named quot and rem. The quotient is rounded towards zero.
The result satisfies quot*denominator+rem = numerator.
The ldiv() and lldiv() and imaxdiv() functions do the same,
dividing numbers of the indicated type and returning the result
in a structure of the indicated name, in all cases with fields
quot and rem of the same type as the function arguments.
RETURN VALUE
The div_t (etc.) structure.
EXAMPLE
After
div_t q = div(-5, 3);
the values q.quot and q.rem are -1 and -2, respectively.
CONFORMING TO
SVID 3, BSD 4.3, ISO 9899.
The functions lldiv() and imaxdiv() were added in ISO C99.
SEE ALSO
abs(3)
2003-11-01 DIV(3)
Bjarne Stroustrup, "The C++ Programming Language: Third Edition",
Chapter 22 Numerics, Section 3 Standard Mathematical Functions, page 661

"For historical reasons,
a few mathematical functions are found in the <cstdlib> header
rather than in <cmath>."
Jul 22 '05 #6

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:cs**********@nntp1.jpl.nasa.gov...
Howard wrote:
I know [that] I can do integer division with operator/
and get the [remainder] with operator%
but is there any function that calculates both values in one shot?


Bjarne Stroustrup, "The C++ Programming Language: Third Edition",
Chapter 22 Numerics, Section 3 Standard Mathematical Functions, page 661

"For historical reasons,
a few mathematical functions are found in the <cstdlib> header
rather than in <cmath>."


You know, I had my book open to that page when I wrote this, and I never saw
those div functions. I must be going blind! (Probably all that, well, you
know...)

Thanks one and all!

-Howard
Jul 22 '05 #7

"Howard" <al*****@hotmail.com> wrote in message
news:pw*******************@bgtnsc05-news.ops.worldnet.att.net...
I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both values in one shot? It seems quite wasteful in time to do the division
twice in order to get both of those values, when it would be quite easy to
return them both from a single function.


I'd just get a good optimizing compiler. Consider:

#include <stdio.h>
void foo(int a, int b)
{
int c;
int d;
c = a / b;
d = a % b;
printf("%d %d\n", c, d);
}

Compiling it with Digital Mars C++ gives:

_foo:
push EAX
mov EAX,8[ESP]
cdq
idiv dword ptr 0Ch[ESP]
push EDX
push EAX
push offset FLAT:_DATA
call near ptr _printf
add ESP,0Ch
pop EAX
ret

No need to muck about with special functions, inline assembler, etc.

-Walter
www.digitalmars.com C, C++, D compilers
"code of the nerds"
Jul 22 '05 #8
On Fri, 21 Jan 2005 13:13:05 -0800, Andrey Tarasevich
<an**************@hotmail.com> wrote in comp.lang.c++:
Howard wrote:
I know I can do integer division with the / operator, and get the
modulus with the % operator, but is there any function that calculates both
values in one shot?


Yes. It is called 'div' ('ldiv'). It is inherited from C standard
library. However, how exactly it calculates these values depends on the
concrete implementation.


No it doesn't. C++ inherits the C90 definition of 'div' and 'ldiv':

<quote>
4.10.6.2 The div function

Synopsis

#include <stdlib.h>
div_t div(int numer, int denom);

Description

The div function computes the quotient and remainder of the
division of the numerator numer by the denominator denom . If the
division is inexact, the sign of the resulting quotient is that of the
algebraic quotient, and the magnitude of the resulting quotient is the
largest integer less than the magnitude of the algebraic quotient. If
the result cannot be represented, the behavior is undefined;
otherwise, quot * denom + rem shall equal numer .

Returns

The div function returns a structure of type div_t , comprising
both the quotient and the remainder. The structure shall contain the
following members, in either order.

int quot; /* quotient */
int rem; /* remainder */
<unquote>

So how is this implementation-defined?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #9
Jack Klein wrote:
Andrey Tarasevich wrote:
Howard wrote:
I know [tht] I can do integer division with operator/
and get the modulus with operator%
but is there any function that calculates both values in one shot?
Yes. It is called 'div' ('ldiv').
It is inherited from C standard library. However,
how exactly it calculates these values
depends on the concrete implementation.


No it doesn't. C++ inherits the C90 definition of 'div' and 'ldiv':

<quote>
4.10.6.2 The div function

Synopsis

#include <stdlib.h>
div_t div(int numer, int denom);

Description

The div function computes the quotient and remainder of the
division of the numerator numer by the denominator denom . If the
division is inexact, the sign of the resulting quotient is that of the
algebraic quotient, and the magnitude of the resulting quotient is the
largest integer less than the magnitude of the algebraic quotient.
the result cannot be represented, the behavior is undefined;
If otherwise, quot * denom + rem shall equal numer .

Returns

The div function returns a structure of type div_t , comprising
both the quotient and the remainder. The structure shall contain the
following members, in either order.

int quot; /* quotient */
int rem; /* remainder */
<unquote>

So how is this implementation-defined?

Bjarne Stroustrup, "The C++ Programming Language: Third Edition",
Chapter 22 Numerics, Section 3 Standard Mathematical Functions, page 661

struct div_t { implementation_defined quot, rem; };
struct ldiv_t { implementation_defined quot, rem; };

The data representation is implementation defined and, of course,
div(int, int), div(long int, long it) and ldiv(long int, long in)
could be implement in assembler
or as C or C++ external or inline functions
which may or may not invoke
any combination of operator/ and/or operator%.
Jul 22 '05 #10
Walter wrote:
I'd just get a good optimizing compiler. Consider:

#include <stdio.h>
void foo(int a, int b)
{
int c;
int d;
c = a / b;
d = a % b;
printf("%d %d\n", c, d);
}

Compiling it with Digital Mars C++ gives:
GCC optimizes it away, too:
foo:
pushl %ebp
movl %esp, %ebp
subl $12, %esp
movl 8(%ebp), %edx
movl %edx, %eax
sarl $31, %edx
idivl 12(%ebp)
pushl %edx
pushl %eax
pushl $.LC0
call printf
leave
ret
.size foo, .-foo
.ident "GCC: (GNU) 3.3.1 (SuSE Linux)"
No need to muck about with special functions, inline assembler, etc.

-Walter
www.digitalmars.com C, C++, D compilers


No need to buy a compiler SCNR

Christian
Jul 22 '05 #11
Christian Gollwitzer wrote:
Walter wrote:
I'd just get a good optimizing compiler. Consider:

#include <stdio.h>
void foo(int a, int b)
{
int c;
int d;
c = a / b;
d = a % b;
printf("%d %d\n", c, d);
}

Compiling it with Digital Mars C++ gives:

GCC optimizes it away, too:


So does VC++ 2003:

void foo(int a, int b)
{
int c,d;
c = a / b;
d = a % b;
00401000 mov eax,dword ptr [esp+4]
00401004 cdq
00401005 idiv eax,dword ptr [esp+8]
00401009 push esi
printf("%d %d\n", c, d);
0040100A push edx
0040100B push eax
0040100C push offset string "%d %d\n" (406100h)
00401011 call printf (40105Bh)

It optimizes even if there are other statements between division and
remainder calculation:

int c,d,k,f;
c = a / b;
00401000 mov eax,dword ptr [esp+4]
00401004 cdq
00401005 idiv eax,dword ptr [esp+8]
00401009 push esi
k = c+2;
0040100A lea ecx,[eax+2]
f = 2*k;
0040100D lea esi,[ecx+ecx]
d = a % b;
printf("%d %d %d %d\n", c, d, k, f);
00401010 push esi
00401011 push ecx
00401012 push edx
00401013 push eax
00401014 push offset string "%d %d %d %d\n" (406100h)
00401019 call printf (40105Bh)

so there's no need at all for hand-made optimization.

cu
Martin
Jul 22 '05 #12

"Martin Stettner" <no****@martin.dot.stettner.at.complement.dot.at > wrote in
message news:cs**********@newsreader1.utanet.at...
Christian Gollwitzer wrote:
Walter wrote:
I'd just get a good optimizing compiler. Consider:

#include <stdio.h>
void foo(int a, int b)
{
int c;
int d;
c = a / b;
d = a % b;
printf("%d %d\n", c, d);
}

Compiling it with Digital Mars C++ gives:

GCC optimizes it away, too:


So does VC++ 2003:

void foo(int a, int b)
{
int c,d;
c = a / b;
d = a % b;
00401000 mov eax,dword ptr [esp+4]
00401004 cdq
00401005 idiv eax,dword ptr [esp+8]
00401009 push esi
printf("%d %d\n", c, d);
0040100A push edx
0040100B push eax
0040100C push offset string "%d %d\n" (406100h)
00401011 call printf (40105Bh)

It optimizes even if there are other statements between division and
remainder calculation:

int c,d,k,f;
c = a / b;
00401000 mov eax,dword ptr [esp+4]
00401004 cdq
00401005 idiv eax,dword ptr [esp+8]
00401009 push esi
k = c+2;
0040100A lea ecx,[eax+2]
f = 2*k;
0040100D lea esi,[ecx+ecx]
d = a % b;
printf("%d %d %d %d\n", c, d, k, f);
00401010 push esi
00401011 push ecx
00401012 push edx
00401013 push eax
00401014 push offset string "%d %d %d %d\n" (406100h)
00401019 call printf (40105Bh)

so there's no need at all for hand-made optimization.

cu
Martin


That's pretty cool. When I started coding (back in the stone age), hand
optimizations were pretty much required. Glad to see that compilers have
come so far.

Thanks, everyone!

-Howard


Jul 23 '05 #13
Jack Klein wrote:
...
Yes. It is called 'div' ('ldiv'). It is inherited from C standard
library. However, how exactly it calculates these values depends on the
concrete implementation.


No it doesn't. C++ inherits the C90 definition of 'div' and 'ldiv':
...
So how is this implementation-defined?
...


I never said that specification of this function depends on the
implementation. By "depends on the concrete implementation" I meant that
there's no guarantee that the actual implementation if 'div'/'ldiv'
functions is different from a simple application of '/' and '%', i.e.
there is no guarantee that 'div'/'ldiv' is more efficient in OP's case
even if we assume that there's no function call overhead.

--
Best regards,
Andrey Tarasevich
Jul 23 '05 #14

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

Similar topics

28
by: Timothy Madden | last post by:
Hello I've read here that only C language has a standard 64bit integer. Can you please tell me what are the reasons for this ? What is special about C language ? Can you please show me some...
17
by: Christopher Dyken | last post by:
Hi group, I'm trying to implement two routines to handle 32x32-bits and 64x64-bits signed integer multiplication on a 32 bits machine in C. It easy to find descriptions of non-signed...
38
by: Keith | last post by:
I've been reading and looking on the internet - but I just can't fin this. Perhaps I'm approaching this the wrong way - code-wise I'm attempting to learn how "things" work in VBNET by creating...
3
by: anon | last post by:
I want to obtain the appearance of frozen columns as in an excel sheet so thet the first two columns of the table remain in view at all times. Example - I have a table of products - listed by...
13
by: moondaddy | last post by:
my understanding is that the max value of a byte is 255. Therefore, why does the following code get a compile error? byte val1 = 10; byte val2 = 23; byte ttl; ttl = val1 + val2; //this line...
12
by: Godzilla | last post by:
Hello, I'm trying to find a way to convert an integer (8-bits long for starters) and converting them to a list, e.g.: num = 255 numList = with the first element of the list being the...
130
by: euler70 | last post by:
char and unsigned char have specific purposes: char is useful for representing characters of the basic execution character set and unsigned char is useful for representing the values of individual...
4
by: begoddendave | last post by:
Hi I am trying to add 2 variables together but I think the computer see's the numbers as a string instead of an integer. I have looked for help with this but all I can see is ASP doesn't allow...
30
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Let's say we had a simple function for returning the amount of days in a month: unsigned DaysInMonth(unsigned const month) { switch (month) { case 8: case 3: case 5:
3
by: SavRak | last post by:
Hi, I seem to be having an issue linking my XML document and XML Schema together. Both are not working, and do not seem to be validating when using: http://tools.decisionsoft.com/schemaValidate/ ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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,...
0
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...

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.