Find if a part of the integer from another integer is divisible by 7?

The question states:

Given an integer A, and two indices Li, Ri. Find if the number from A which is bounded by the two indices is divisible by 7?

For example if A = 357753
indices Li = 3, Ri = 4, then the number is 77, which is divisible.

My program give a time limit exceeded when executed for larger numbers. Are there any other performance improvement can be done in my code. Or the whole method is wrong for the solution. Any help would be appreciated.

First code (not optimized):

inp = raw_input()  q = input()    temp = ""  for i in range(q):      l, r = map(int, raw_input().split())      temp =  int(inp[l - 1:r])      if temp % 7 == 0:          print "YES"     else:          print "NO"

My second program is:

inp = input()  q = input()  temp = 0 length = len(str(inp)) - 1 for i in range(q):      left, right = map(int, raw_input().split())      temp = inp     end = length - right + 1     temp = temp / (10 ** end)     mul = 1     final = 0      while right >= left:          cur = temp % 10         temp = temp / 10         right -= 1         #print cur         final += (cur * mul)         mul = mul * 10       if final % 7 == 0:          print "YES"     else:          print "NO"

Replay

Category: python Time: 2016-07-31 Views: 4