Im currently working on this code wars pisano period.
We need to return the length of the period by which you divide the fibonacci sequence.
The python code I searched for on youtube looks like this. Also its important to note that the python function returns the entire modulo version of the fibonacci sequence instead of the length
here is the youtube video from which I got this answer from Lets Python: Pisano
def pisanoPython(divisor):
'''Returns a modulo version of the Fibonacci sequence'''
fib = [0,1]
while True:
fib.append((fib[-1]+fib[-2]) % divisor)
if fib[-1] == 1 and fib[-2] == 0:
return fib[:-2]
>>>pisano(3)
[0,1,1,2,0,2,2,1]
Below is my code (which is giving me the wrong output)
function pisanoJavascript(n){
let fib = [0,1];
let isRepeated = true;
while(isRepeated) {
let lastVal = fib[fib.length-1]
let secondLastVal = fib[fib.length-2]
let remainder = (lastVal + secondLastVal) % n
fib.push(remainder)
if(lastVal === 1 && secondLastVal === 0) isRepeated = false
}
return fib.slice(0,-2).length
}
I followed the logic and the steps from the python function but can’t figure out which part I am missing.
I find that the line
if(lastVal === 1 && secondLastVal === 0) isRepeated = false
. will always hit and break out of the while loop so maybe I need to initialize fib array in a different way. Why are these two functions not the same even though I followed the logic from pisanoPython
and how can I make the javascript version work