PE_26

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值