Blue Bridge Cup - the first n decimal place (python language)



Ideas:
the value of n is large, precision Python, subtraction, multiplication operator comes okay, we did not find a division own methods.
It is necessary to simulate the process of division, to n / m Example:
n-> = m: the m // List n-,% n-m = n-
n-<m: n-m * 10 // the supplier, n = n * 10% m
(written calculation about the process can be derived 100/3)

At the same time, the title gives the pruning conditions, either finite decimal, or infinite decimals
how to deal with recurring decimal? -> n, usage records (i.e., check [x] = n = to x, corresponds to the first of several decimal), a long time n has been accessed, then the cycle represents occurred. Then loop back to the string part of the direct splicing can, in fact, can also be optimized without stitching, directly from the difference between the current length of the string and the target length, were taken over balabla, should be faster (not want to write ..

Code:

n, m, t = list(map(int, input("").split(" ")))
while n >= m:
    n = n % m
# 当前正在计算小数第几位
i = 0
# 结果字符串
s = ""
# 记录n的使用情况
check = {}
# n < m
while n:
    if n in check:
        # 表示开始出现了循环,找到上一个n的位置
        last = check[n]
        # 循环的部分是last~i-1
        circle = s[last:i]
        # 这里+10就是保证字符串的长度足够(加上其他的也可以
        s += ((t-i)//len(circle) + 10) * circle
        break
    check[n] = i
    s += str(n*10//m)
    n = n*10%m
    i += 1
    if i == t+10:
        break
s = s[t-1:t+2]
# 不足的补上"0"
s += (3 - len(s)) * "0"
print(s)

Guess you like

Origin www.cnblogs.com/NFii/p/12391109.html