Re: division by 7 without using division operator
- From: "Harald van Dijk" <truedfx@xxxxxxxxx>
- Date: 6 Feb 2007 00:58:46 -0800
Richard Heathfield wrote:
CBFalconer said:
"*** T. Winter" wrote:
"Francois Grieu" <fgrieu@xxxxxxxxx> writes:
...
To suceed in these interviews, I fear that you must not be so
smart as to outsmart the person asking the questions. So I
suspect the right answer might have been
number *= 0.142857142857143; // divide by 7
which indeed, in quite a few contexts, is an approriate answer.
Indeed, it gives the correct answer for all integers from 0 to
2147483647.
And probably down to -2147483648.
An exercise for those with way too much time on their hands: what is the
smallest-magnitude integer (i.e. regardless of sign) for which it
fails? If this number is negative, what is the smallest *positive*
integer for which it fails?
It depends on the implementation's precision and the rounding mode.
One possible answer: C90 (but not C99) allows integer division to
round towards negative infinity, so -1 / 7 could be -1, but -1 *
0.142857142857143 is always 0.
Mathematically, 0.142857142857143 is equal to 1.000000000000001 / 7,
so another possible answer is easy to guess and confirm:
100000000000000.
100000000000000 * 0.142857142857143 is 142857142857143
100000000000000 / 7 is 142857142857142.8..., which becomes
142857142857142 because floating point to integer conversions round
towards zero. For any smaller positive number, the exact difference
between the two numbers cannot be greater than 1/7, so when rounding
towards zero, it cannot make a difference. Also, when rounding towards
zero, the sign doesn't matter.
There are other possible answers depending on the representation of
double.
.
- References:
- division by 7 without using division operator
- From: krypto . wizard
- Re: division by 7 without using division operator
- From: Francois Grieu
- Re: division by 7 without using division operator
- From: *** T. Winter
- Re: division by 7 without using division operator
- From: CBFalconer
- Re: division by 7 without using division operator
- From: Richard Heathfield
- division by 7 without using division operator
- Prev by Date: Re: division by 7 without using division operator
- Next by Date: Re: cat was Re: Malloc
- Previous by thread: Re: division by 7 without using division operator
- Next by thread: Re: division by 7 without using division operator
- Index(es):