我正在尝试编写一个程序来解决此模式,并在 n 位置获取值( n从1到10 ^ 5 不等)
1,2,7,20,61,182 ... Reference
我能够编写一个函数来做到这一点。但是请继续
OverflowError: cannot convert float infinity to integer
较大的 n 输入错误。 但是在 py2 中可以正常工作。
def getPattern(n):
total = 2
tmptotal = 1
count = 2
if(n == 1 or n == 2):
print(n)
else:
for i in range(2, n):
if(count == 2):
total = (total + (total/2))*2 + 1
count = 1
else:
total = (total + ((total-1)/2))*2
count = 2
tmptotal = total
return int(total)
n =int(input())
print(getPattern(n))
因此,我希望在py3 env中解决此错误。
答案 0 :(得分:1)
在python3中,/
是浮点除法的,因此您的total
变量被设为浮点数。 python3中python2代码的等效代码是这样的:
def getPattern(n):
total = 2
tmptotal = 1
count = 2
if n == 1 or n == 2:
print(n)
else:
for i in range(2, n):
if count == 2:
total = (total + (total // 2)) * 2 + 1
count = 1
else:
total = (total + ((total - 1) // 2)) * 2
count = 2
tmptotal = total
return total # No cast needed
n = int(input())
print(getPattern(n))
$ python3 a.py
1000
330517704870201659222613814938036091491355508188037041916230092056707149336676224885194578462652015490977444424218145588987738645525154727966335681314488418506905056299580200969503693557241210318597600029397154510282236953905773609515391543263521668622626544531370086101386763599259723954366342063729034055207567140944645572557104099576971974229639101021224734402343310542961589984673879191254735147027265106522417859716025703587596412186791458002653591533043275692225713805000
$ python2 a.py
1000
330517704870201659222613814938036091491355508188037041916230092056707149336676224885194578462652015490977444424218145588987738645525154727966335681314488418506905056299580200969503693557241210318597600029397154510282236953905773609515391543263521668622626544531370086101386763599259723954366342063729034055207567140944645572557104099576971974229639101021224734402343310542961589984673879191254735147027265106522417859716025703587596412186791458002653591533043275692225713805000