I have a function that takes an integer 'num' and returns any repeating digits in 1 / num. To do this, it takes advantage of a trick in long division. If you keep track of intermediate divisions and see the same division repeat itself, you know that the digits from the first time that division appeared to the previous division are the repeating digits in the decimal. I know this isn't explained well, but here's an example.
Try to run the following code.
def divide_with_repetition_check(num):
"""Determines 1 / num through long division one digit at a time. The function also checks for
repetition, and if there is any,
returns the repeating digits.
It would be better to separate the division functionality out into a generator, and then use
next() to yield each digit
and result combo to check for repetition in a separate function.
For now, this is how it will remain.
Args:
num (int): Denominator for divison
Returns:
string: Repeating digits converted to a string
"""
dividend = 1
zero_count = 0
intermediate_divisions = []
repeating_digits = ""
result = dividend // num
while dividend:
if (num, result) in intermediate_divisions:
index = intermediate_divisions.index((num, result))
for i in range(index, len(intermediate_divisions)):
repeating_digits += str(intermediate_divisions[i][1])
break
if result == 0:
zero_count += 1
intermediate_divisions.append((num, result))
dividend = (
dividend % num * 10
) # This is equivalent to "bringing down the zero" in long divison
result = dividend // num
return repeating_digits
num = 7
repeating_digits = divide_with_repetition_check(num)
print(repeating_digits)
For the purposes of this example, I will show a repeating decimal by putting the repeating digits in brackets. So if 1/3 = 0.3333333333333333..... I would write 0.(3).
With num set to 7, the script prints '142857' since 1/7 = 0.(142857). If you set num to 2, the script prints nothing since 1/2 = 0.5 which contains no repeating decimals.
The problem comes in when you set num to something like 14. 1/14 = 0.0(714285). There is a leading zero here, and the script determines that the zero is the repeating digit and prints '0' instead of '7142285' as it should.
This same issue arises for numbers with a leading zero in the decimal but with no repetition. For example, set num to 16.
Any help is greatly appreciated.