tags:

views:

516

answers:

5

I am trying to find out a^b in python, of really large no.s

My code is this:

t=raw_input()
c=[]
for j in range(0,int(t)):
    n=raw_input()
    a=[]
    a,b= (int(i) for i in n.split(' '))
    c.extend(pow(a,b))
for j in c:
    print j

And I am getting an error like this:

raceback (most recent call last):
  File "C:/Python26/lastdig.py", line 7, in <module>
    c.extend(pow(a,b))
TypeError: 'int' object is not iterable

Whats wrong in my prob and is it an efficent way to find out powers of large numbers?

+1  A: 

You should try GMPY. Try something like:

import gmpy
a = gmpy.mpz(10**10)
b = a**10000000

I don't know how much "big" your numbers are, this solution isn't that fast (but the result is big enough :P )

Andrea Ambu
A: 

Another way you might want to try calculating exponents is by using logarithm laws.

x^y = e^(y ln x)

I can't say for certain but this might reduce the number of operations required to calculate large exponents.

Fredrick Pennachi
no it won't, it'll be 10 times slower
SilentGhost
I am curious to know whether this facilitates a performance benefit; It all depends on python's implementation of pow(). I am waiting for some expert comment on this.
Lakshman Prasad
pow() is done by repeated squaring, so it is very efficient. For moderately sized numbers the logarithm is about the same or slightly faster, but pow() is superior in general because it calculates the exact answer instead of a floating point approximation, and because it won't overflow on large numbers.
Kiv
+1  A: 

python integer ops are arbitrary precision If you want arbitrary precision floating point ops import Decimal

from decimal import *
d=Decimal('2.0')
print d**1234
pixelbeat
+1  A: 

10000**10000 prints in my machine in under a second.

How large is your input.

Your problem is not related to power function.

Use

c.append()

instead of

c.extend()

c.extend takes an iterable (a list/tuple/set/custom iterables) as an input.

Lakshman Prasad
+2  A: 

You are using extend wrong. A.extend( B ), requires that B is some iterable object( ie a list, tuple ). You really want to use append instead.

t=raw_input()
c=[]
for j in range(0,int(t)):
    n=raw_input()
    a,b= (int(i) for i in n.split(' '))
    c.append( pow(a,b) ) ## or you could extend c.extend( [ pow(a,b) ] ), but thats silly.
for j in c:
    print j
Sanjaya R