计算循环小数的周期长度
Calculate period length of recurring decimal fraction
我想在 python (3.6.5) 中编写一个程序来告诉例如1/7。此示例的输出应类似于:"length: 6, repeated numbers: 142857"。到目前为止我得到了这个:
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
函数本身的表示,而不是它的输出。
这是您的代码的修复版本。我使用 Python 3.6+ f-string 将重复数字转换为字符串,并在前面添加零以使其长度正确。
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
这一行可能有点神秘:
f"{z // d:0{k}}"
它说:找到小于或等于z
的最大整数除以d
,将其转换为字符串,并在左侧填充零(如有必要)以给出它的长度为 k
.
正如 Goyo 在评论中指出的那样,该算法并不完美。如果小数包含任何不重复的部分,即如果分母有任何因数 2 或 5,它就会陷入循环。看看你是否能想出一种方法来处理它。
这是我的 Python 实现 https://www.geeksforgeeks.org/find-recurring-sequence-fraction/
def fraction_to_decimal(numerator, denominator):
""" This function returns repeating sequence of a fraction.
If repeating sequence doesn't exits, then returns empty string """
# Create a map to store already seen remainders
# remainder is used as key and its position in
# result is stored as value. Note that we need
# position for cases like 1/6. In this case,
# the recurring sequence doesn't start from first
# remainder.
result = ""
mapping = {}
# Find first remainder
remainder = numerator % denominator
# Keep finding remainder until either remainder
# becomes 0 or repeats
while remainder != 0 and remainder not in mapping:
# Store this remainder
mapping[remainder] = len(result)
# Multiply remainder with 10
remainder = remainder * 10
# Append remainder / denominator to result
result_part = int(remainder / denominator)
result += str(result_part)
# print(f"Result: {result}")
# Update remainder
remainder = remainder % denominator
# print(f"Map: {mapping}")
return result
if __name__ == '__main__':
result = fraction_to_decimal(1, 7)
if result == "":
print("No recurring sequence")
else:
print(f"\nLenght of recurring sequence: {len(result)}")
print(f"\nRecurring sequence is {result}\n")
我想在 python (3.6.5) 中编写一个程序来告诉例如1/7。此示例的输出应类似于:"length: 6, repeated numbers: 142857"。到目前为止我得到了这个:
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
函数本身的表示,而不是它的输出。
这是您的代码的修复版本。我使用 Python 3.6+ f-string 将重复数字转换为字符串,并在前面添加零以使其长度正确。
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
这一行可能有点神秘:
f"{z // d:0{k}}"
它说:找到小于或等于z
的最大整数除以d
,将其转换为字符串,并在左侧填充零(如有必要)以给出它的长度为 k
.
正如 Goyo 在评论中指出的那样,该算法并不完美。如果小数包含任何不重复的部分,即如果分母有任何因数 2 或 5,它就会陷入循环。看看你是否能想出一种方法来处理它。
这是我的 Python 实现 https://www.geeksforgeeks.org/find-recurring-sequence-fraction/
def fraction_to_decimal(numerator, denominator):
""" This function returns repeating sequence of a fraction.
If repeating sequence doesn't exits, then returns empty string """
# Create a map to store already seen remainders
# remainder is used as key and its position in
# result is stored as value. Note that we need
# position for cases like 1/6. In this case,
# the recurring sequence doesn't start from first
# remainder.
result = ""
mapping = {}
# Find first remainder
remainder = numerator % denominator
# Keep finding remainder until either remainder
# becomes 0 or repeats
while remainder != 0 and remainder not in mapping:
# Store this remainder
mapping[remainder] = len(result)
# Multiply remainder with 10
remainder = remainder * 10
# Append remainder / denominator to result
result_part = int(remainder / denominator)
result += str(result_part)
# print(f"Result: {result}")
# Update remainder
remainder = remainder % denominator
# print(f"Map: {mapping}")
return result
if __name__ == '__main__':
result = fraction_to_decimal(1, 7)
if result == "":
print("No recurring sequence")
else:
print(f"\nLenght of recurring sequence: {len(result)}")
print(f"\nRecurring sequence is {result}\n")