1

I implemented an algorithm for finding sums of Pascal's Triangle rows, but it's slowly for the contest. My program passed 4 test cases, but failed in the next case with a runtime error. Can I make my code faster?

import math

n = int(input())

for i in range(n):
    print int(math.pow(2, (int(input())-1)))

Input Format is the first line contains the number of test cases T. Then T test cases follow:

2
1
3
Jota
  • 17,281
  • 7
  • 63
  • 93
Bob Napkin
  • 566
  • 6
  • 15

1 Answers1

1

Math.pow works with floats, so solution may be inexact for large exponent. Moreover, for values over 1023, it throws OverflowError.

Use x ** y operator instead, or builtin pow function.

  • wow, thank you, I passed one test case more, but I have runtime errors 'Terminated due to timeout' as before -(. – Bob Napkin Jul 05 '15 at 05:48
  • 1
    Then you should implement some [fast exponentiation method](https://en.wikipedia.org/wiki/Exponentiation_by_squaring), keeping all intermediate results to answer next test cases efficiently. I think 2k-ary method is a good fit. –  Jul 05 '15 at 06:29