我需要用python写一个程序,它给出一个整数作为输入,计算从1开始到无穷大的连续自然数行中的数字(例如。12345678910111213141516171819202122等...)例如,如果我们输入17,它将计算此行中的第17位数字,即3。
我已经写了一个程序,可以计算到第189位,但我需要使它非常大的数字(直到位置2**31-1)
def digit_finder():
if pos < 10: #Position is equal to digit.
digit=pos
return(digit)
elif pos >= 10 en pos < 189: #Number between 10 and 99.
number=(pos-9)
if pos%2==0:
new_number=(10+(number//2))
digit=(new_number//10)
return digit
else:
new_number=(9+(number//2))
digit=(new_number-((new_number//10)*10))
return digit我不知道如何继续处理更大的数字。请帮帮我!
发布于 2013-10-16 05:39:49
一种方法是将每个数字转换为一个字符串,并将它们链接在一个无限的生成器中。然后你从一开始就忽略一定数量的字符,然后取下一个...,例如:
from itertools import chain, count, islice
def digit_finder(n):
digits = chain.from_iterable(str(i) for i in count(1))
return int(next(islice(digits, n - 1, None)))
print(digit_finder(17))发布于 2014-01-04 03:13:53
这可以使用两个方程来解决,这两个方程将生成第n位数字。请看这里:https://math.stackexchange.com/a/626217/48057和这里:https://myows.com/protects/copyright/67407_mathexploration-pdf。
在第二个链接中,请通读第9- 12页(特别是12页,因为有一些关于如何实现它的提示。
https://stackoverflow.com/questions/19391152
复制相似问题