1

我需要在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

我不知道如何继续更大的数字。请帮忙 !

4

2 回答 2

1

One way is to convert each number to a string and chain them all together in an endless generator. You then ignore from the start a certain amount of characters, and then take the next one..., eg:

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))
于 2013-10-15T21:39:49.163 回答
1

这可以使用将生成第 n 个数字的两个方程来解决。请看这里:https ://math.stackexchange.com/a/626217/48057 和这里:https ://myows.com/protects/copyright/67407_mathexploration-pdf 。

在第二个链接中,请通读 p。9-12(特别是 12,因为有一些关于如何实现它的提示。

于 2014-01-03T19:13:53.130 回答