How to multiply big numbers faster?
<p>I was experimenting with multiplying large numbers in python. For my purpose I was trying to evaluate. </p>

<pre><code>2*odd*(4*odd^2 + 7)/3 - 6*odd^2 - 3
</code></pre>

<p>Now my question boils down to how to multiply numbers faster in python. is it faster to do it with float? The answer seems no. Take a simpler example with </p>

<blockquote>
  <p>n*(n+1)/2</p>
</blockquote>

<p>My idea was that the following code is faster</p>

<pre><code>product = 1
if n % 2 == 0:
    product *= n/2
    product *= n
else:
    product *= (n+1)/2
    product *= n
return product
</code></pre>

<p>Why would this be faster? Well you would not have to divide the huuge number <code>n*(n+1)</code> by two. However one does waste a calculation checking the number modulo2. Perhaps <code>try exception</code> is faster? </p>

<p>So my question boils down to. How does one compute the product and division of very large numbers in python? Here is my working code. Not asking for specifically speed improvements on this code. But the more broad question on how to deal with division and multiplication of large numbers. My numrange is around <code>10^(10^6)</code> atm.</p>

<pre><code>def spiral_sum_fast(num):
    rem = num % 6
    if rem % 2 == 0:
        raise Exception("The sidelength must be a odd number")
    odd = 1 + num / 2
    odd_squared = 2 * odd**2

    if rem % 3 == 0:
        temp = odd / 3
        temp *= 8 * odd_squared + 14
    else:
        temp = (4 * odd_squared + 7) / 3
        temp *= 2 * odd
    return temp - 3 * odd_squared - 3


if __name__ == '__main__':

    k = 10**(10**6) + 1
    spiral_sum_fast(k)
</code></pre>