(-1)**1000

Albert van der Horst albert at spenarnc.xs4all.nl
Mon Nov 3 19:46:06 EST 2014


In article <mailman.15076.1413990100.18130.python-list at python.org>,
Ned Batchelder  <ned at nedbatchelder.com> wrote:
>On 10/22/14 5:27 AM, ast wrote:
>>
>> "Chris Angelico" <rosuav at gmail.com> a écrit dans le message de
>> news:mailman.15058.1413968065.18130.python-list at python.org...
>>> On Wed, Oct 22, 2014 at 7:27 PM, ast <nomail at invalid.com> wrote:
>>>> If i am writing (-1)**1000 on a python program, will the
>>>> interpreter do (-1)*(-1)*...*(-1) or something clever ?
>>>>
>>>> In fact i have (-1)**N with N an integer potentially big.
>>>
>>> Exponentiation is far more efficient than the naive implementation of
>>> iterated multiplication.
>>
>> In the very particular case of (-1)**N,  I belive that Python check
>> the odd or even parity of N and provides the result accordingly.
>>
>> I tried:
>>>>> (-1)**1000000000000000000000000000000000
>> 1
>>>>> (-1)**1000000000000000000000000000000001
>> -1
>>
>> and it is instantaneous
>>
>>
>
>Keep in mind that actually calculating the exponentiation wouldn't do
>1000000000000000000000000000000000 multiplications anyway: the clever
>way to do integer powers is by squaring based on the binary
>representation of the exponent.  It's explained here:
>http://stackoverflow.com/a/101613/14343
>
>So even if Python is actually calculating the value, it's only doing 75
>multiplications or so.

I'm pretty sure that if we replace -1 by 2 , it never gets at its 75-th
multiplication.

>
>--
>Ned Batchelder, http://nedbatchelder.com
>
Groetjes Albert
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst




More information about the Python-list mailing list