长分1 / n的问题

时间:2014-09-24 04:40:39

标签: python loops math division

我已编写以下代码以返回1 / n的重复次数。它基本上执行长期除法,直到它达到重复红利。直接拨打repetends(n)会返回正确的结果,例如repetends(7)返回(True, '142857'),意味着1/7确实具有无限重复的十进制重复次数142857.

但是,当我致电list_repetends(10)时,只是在for循环中调用repetends上升到某个n,我就会因为单独调用repetends而产生完全不同 - 而且不正确在n = 1,2,3 ...... 10上。

以下是我得到的结果,然后是代码。知道为什么一个简单的for循环会搞砸我的结果吗?

n,repetends(n),list_repetends(10):

1(错误,' 1')(错误,' 1')

2(错误,' 5')(错误,' 15')

3(True,' 3')(True,' 3')

4(错误,' 25')(正确,' 3')

5(错误,' 2')(正确,' 3')

6(是的,' 6')(正确,' 3')

7(True,' 142857')(正确,' 3')

8(错误,' 125')(正确,' 3')

9(True,' 1')(True,' 3')

10(假,' 1')(正确,' 3')

f = ''
remainders = {}

# n = numerator (1), d = denominator, z = tracks dropped zeros

def longdiv(n, d, z):
    global remainders
    global f
    if n in remainders:
        return True, f[remainders[n]:]
    mod = n % d
    if mod == n:
        if z >= 1:
            f += '0'
        z += 1
        return "Cont", (10*n, d, z)
    else:
        if mod == 0:
            f += str(n/d)
            return False, f
        else:
            r = n - mod
            dec = r/d
            f += str(dec)
            if n not in remainders:
                remainders[n] = len(f)-1
            return "Cont", (mod, d, 0)

def repetends(n):
    div, rem = longdiv(1,n,0)
    if div == True or div == False:
        return div, rem
    else:
        while div == "Cont":
            mod, d, z = rem
            div, rem = longdiv(mod,n,z)
        return div, rem

def list_repetends(n):
    for i in range(1,n+1):
        print repetends(i)

0 个答案:

没有答案