division by 7 efficiently ???

John Machin sjmachin at lexicon.net
Fri Feb 2 10:49:33 EST 2007


On Feb 3, 2:31 am, "Jesse Chounard" <jessechoun... at gmail.com> wrote:
> On 31 Jan 2007 19:13:14 -0800, krypto.wiz... at gmail.com
>
> <krypto.wiz... at gmail.com> wrote:
> > Its not an homework. I appeared for EA sports interview last month. I
> > was asked this question and I got it wrong. I have already fidlled
> > around with the answer but I don't know the correct reasoning behind
> > it.
>
> I think this works:

You think wrongly. Inspection reveals that it is obviously incorrect
for N == 0. Trivial testing reveals that it is wrong for about 6 out
of every 7 cases.

>
> >>> def div7 (N):
>
> ...     return ((N * 9362) >> 16) + 1
> ...>>> div7(7)
> 1
> >>> div7(14)
> 2
> >>> div7(700)
> 100
> >>> div7(70000)
>
> 10000
>
> The coolest part about that (whether it works or not) is that it's my
> first Python program.  I wrote it in C first and had to figure out how
> to convert it.  :)

Try testing algorithms with a pencil on the back of an envelope first.

The uncoolest part about that is that your test data is horribly
deficient:

>>> for N in xrange(0, 23):
...     a = ((N * 9362) >> 16) + 1
...     e = N // 7
...     print N, a, e, a == e
...
0 1 0 False
1 1 0 False
2 1 0 False
3 1 0 False
4 1 0 False
5 1 0 False
6 1 0 False
7 1 1 True
8 2 1 False
9 2 1 False
10 2 1 False
11 2 1 False
12 2 1 False
13 2 1 False
14 2 2 True
15 3 2 False
16 3 2 False
17 3 2 False
18 3 2 False
19 3 2 False
20 3 2 False
21 3 3 True
22 4 3 False

HTH,
John




More information about the Python-list mailing list