I am writing a code which returns something like 1^k + 2^k + 3^k......n-1 where k be any number.Below is my code.I am getting a memory error.How do I optimise it. Sample test case for wrong error:

1 10000000000000000 400

    import sys

def highwayConstruction(n, k):
    # Complete this function
    for i in range(1,n-1):
    return sum    

q = int(raw_input().strip())
print "Qw"
for a0 in xrange(q):
    n, k = raw_input().strip().split(' ')
    n, k = [long(n), int(k)]
    result = highwayConstruction(n, k)
    print result

closed as off-topic by Vogel612, jonrsharpe, Grajdeanu Alex., Mathias Ettinger, Mast Nov 19 '17 at 18:50

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. After the question has been edited to contain working code, we will consider reopening it." – jonrsharpe, Grajdeanu Alex., Mathias Ettinger, Mast
If this question can be reworded to fit the rules in the help center, please edit the question.


Try using xrange instead of range. They both provide a way to generate a list of integers for you to use. The only difference is that range returns a Python list object and xrange returns an xrange object. You get the MemoryError because the list you are trying to generate is too big. I tried running it with xrange and it didn't crash. I waited for about 30 minutes and it's still running.

  • \$\begingroup\$ but now it gives me a timeout error. \$\endgroup\$ – Leo B Jacob Nov 19 '17 at 18:48
  • \$\begingroup\$ This probably means your cpu can't handle this calculation. \$\endgroup\$ – Mixhab Nov 19 '17 at 18:50
  • \$\begingroup\$ is there any other way to do this like bitwise implementation. \$\endgroup\$ – Leo B Jacob Nov 19 '17 at 19:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.