https://projecteuler.net/problem=26
problem 26
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666…, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
就是求 循环小数 长度最大的那个数
分析:
之所以会出现循环小数, 是因为余数的再重现
例如1/6 余数是 1、 4、4、4、4、… 1/7的余数是1 、3、2、6、4、5、1、3、2、….
1、div(1, n)函数 --> 产生余数
2、get_length(1, b)函数 --> 调用div(1,b ), 存储余数到列表中,直到某个余数k重复出现, 输出循环小数的长度== len([第一次出现k, ..,])
3、主函数获取1–>1000每个数的get_length值, 寻找最大的一个即可
def div(a, b):
remained = None
while remained!=0:
if a > b:
quotients, remained = a/b, a%b
yield quotients, remained
a = remained
else:
a *= 10
def get_length(a, b, print_detail=False):
res = div(a, b)
remained=list()
for ele in res:
if print_detail:
print ele
if ele[1] in remained:
return len(remained[remained.index(ele[1]):])
else:
remained.append(ele[1])
return 0
def main():
_max_length = _max_value = 0
for value in xrange(1,1000):
temp = get_length(1,value)
if temp > _max_length:
_max_length, _max_value = temp, value
return _max_value
if __name__=="__main__":
import sys
get_v = sys.argv[1:]
if len(get_v)<2:
print main()
else:
print get_length(int(get_v[0]), int(get_v[1]))
1
lqe:py lqe$ python division.py 1 7
6
lqe:py lqe$ python division.py 1 9
1
lqe:py lqe$ python division.py 1 8
0
lqe:py lqe$ python division.py
983