I have to make a function that does the division 1/7 and prints the digit n of the decimal expansion of 1/7.
The decimal expansion of 1/7 is a 6-digit repeating decimal with the digits 142857.
For example:
n = 2
Position 2 is 1[4]2857.
In other words, it should return 4.
What I did was first limit the expansion to position n and then extract the last number. In this way:
def truncate():
num = 1/7 #0.14285714285714285
cant_decimals = 2
positions = pow(10.0, cant_decimals)
return math.trunc(positions * num) / positions
truncate()
Here it returns 0.14, but I want it to return only 4 and I can’t think of how to do it, since I can’t use lists or strings, please help!
>Solution :
- Make your digit the first one before the decimals, by multiplying it by 10 raised by the power of the decimal position of the digit itself
- then find the remainder of that number divided by 10, which is your digit
num = 1/7 #0.14285714285714285
def find_digit(number, decimal_position):
if decimal_position < 1:
raise Exception("decimal_position < 1")
return int(number * 10 ** decimal_position) % 10
find_digit(num, 2) # 4