Testing for integer result

D

DavidW

Hello,

What is the most reliable way, or the standard way, of determining whether an
integer division operation produces an integer result? I'm using this at
present:

long n1;
long n2;

// stuff
....

// n1, n2 != 0
if(n1/n2 == (double)n1/n2)
{
....
}

I can't see how that can fail, excluding cases of overflow or underflow, but I
thought I'd better ask. I'm using VC++ 6.0.
 
V

Vaclav Haisman

DavidW wrote, On 4.1.2011 22:38:
Hello,

What is the most reliable way, or the standard way, of determining whether an
integer division operation produces an integer result? I'm using this at
present:

long n1;
long n2;

// stuff
...

// n1, n2 != 0
if(n1/n2 == (double)n1/n2)
{
...
}

I can't see how that can fail, excluding cases of overflow or underflow, but I
thought I'd better ask. I'm using VC++ 6.0.
Try std::fmod(), e.g. 'if (std::fmod (n1, n2) == 0)'. It is the floating
point version of operator %.
 
D

DavidW

Pete said:
Integer division operations always produce integer results.

I meant a division of one integer value by another, in mathematics.
If n1%n2 is zero, then n1 is an exact multiple of n2.

Of course, and I've used that plenty of times before. It's been ages since I've
needed to do it. Thanks.

*embarrassed*
 
D

DavidW

Paavo said:
The long datatype is 32 bits with VC++. If this is not sufficient a
logical step would be to use a 64-bit integer type (called __int64 in
VC++6 IIRC). Modern compilers provide int64_t through <stdint.h>.
There are variants of stdint.h also usable with VC++6 (see the end of
http://en.wikipedia.org/wiki/Stdint.h).

Yes, I've written it with a typedef to compile it with __int64. As it turns out,
32-bit ints are enough. I didn't bother to calculate it out before. The maximum
value with the restrictions imposed by the rules is 100*75*50*25*10*10 =
937,500,000, which is less than 2^31. But I might use __int64 anyway so
experiments can be done without restrictions except on the maximum for an item
value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top