formula of the calculation code is good or not?
It is time to take a piece of paper and a pencil and work through the formula manually and then compare that to what the computer gives.
One thing that is missing is the logic for this:
(not in the list)
. ...until you find the first n in the list below.