计算循环十进制小数的周期长度 [英] Calculate period length of recurring decimal fraction

查看:215
本文介绍了计算循环十进制小数的周期长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python(3.6.5)中编写一个程序来说明例如1/7.对于此示例,输出应类似于:长度:6,重复数字:142857".到目前为止,我已经知道了:

I want to do a program in python (3.6.5) that tell the length of e.g. 1/7. The output should be for this example something like: "length: 6, repeated numbers: 142857". I got this so far:

n = int(input("numerator: "))
d = int(input("denominator: "))

def t(n, d):
    x = n * 9
    z = x
    k = 1
    while z % d:
        z = z * 10 + x
        k += 1
        print ("length:", k)
        print ("repeated numbers:", t)

    return k, z / d

t(n, d)

推荐答案

执行print ("repeated numbers:", t)会打印t函数本身的表示形式,而不是其输出.

Doing print ("repeated numbers:", t) prints the representation of the t function itself, not its output.

这是您代码的经过修复的版本.我使用Python 3.6+ f字符串将重复的数字转换为字符串,并在前面添加零以使其长度正确.

Here's a repaired version of your code. I use a Python 3.6+ f-string to convert the repeating digits to a string, and add zeros to the front to make it the correct length.

def find_period(n, d):
    z = x = n * 9
    k = 1
    while z % d:
        z = z * 10 + x
        k += 1

    digits = f"{z // d:0{k}}"
    return k, digits

# Test

num, den = 1, 7
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)

num, den = 1, 17
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)

输出

num: 1 den: 7 period: 6 digits: 142857
num: 1 den: 17 period: 16 digits: 0588235294117647


这行可能有点神秘:


This line may be a bit mysterious:

f"{z // d:0{k}}"

它说:找到小于或等于z除以d的最大整数,将其转换为字符串,并在左侧用零填充(如有必要),以使其长度为.

It says: Find the largest integer less than or equal to z divided by d, convert it to a string, and pad it on the left with zeroes (if necessary) to give it a length of k.

正如Goyo在评论中指出的那样,该算法并不完美.如果小数部分包含任何非重复部分,即分母具有2或5的因数,它将陷入循环.

As Goyo points out in the comments, this algorithm is not perfect. It gets stuck in a loop if the decimal contains any non-repeating part, that is, if the denominator has any factors of 2 or 5. See if you can figure out a way to deal with that.

这篇关于计算循环十进制小数的周期长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆