简体   繁体   中英

Calculate Pisano period given length of sequence and modulus

#This one doesn't work 
def pisano(n,m):
    lis=[]
    for i in range(n+1):
        if i<=1:
            lis.append(i)
        else:
            lis.append((lis[i-2]+lis[i-1])%m)
            if lis[-2:] == [0,1]:
                pisanoo = len(lis)-2
                rem = n%pisanoo
                print(rem)
                calc_fib(rem,m)
                break

#This one works 
def pisano(n,m):
    lis=[0,1]
    while True:
        lis.append((lis[-2]+lis[-1])%m)
        if lis[-2:] == [0,1]:
            pisanoo = len(lis)-2
            rem = n%pisanoo
            print(rem)
            calc_fib(rem,m)
            break

In the code snippet above,'n' is length and 'm' is modulus. My first function that uses 'i' as an iteration fails, but the second function when I the remove the 'i',it successfully calculates the pisano period. Can someone tell me what goes wrong in the first one their logic seems the same.Thanks !

In the first function you are searching n elements, so if pisano happens at a later index your function misses it. In the second function you have an infinite loop, therefore you are searching until you find pisano.

For instance pisano(5,3) happens when len(lis) = 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM