Calculate Period Length Of Recurring Decimal Fraction
Solution 1:
Doing print ("repeated numbers:", t)
prints the representation of the t
function itself, not its output.
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.
deffind_period(n, d):
z = x = n * 9
k = 1while 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)
output
num: 1 den: 7 period: 6 digits: 142857num: 1 den: 17 period: 16 digits: 0588235294117647
This line may be a bit mysterious:
f"{z // d:0{k}}"
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
.
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.
Solution 2:
This is my Python Implementation of https://www.geeksforgeeks.org/find-recurring-sequence-fraction/
deffraction_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 repeatswhile remainder != 0and remainder notin 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")
Post a Comment for "Calculate Period Length Of Recurring Decimal Fraction"