question : how many different ways are there to climb a staircase with n steps (for example, 100...
TRANSCRIPT
Question:
How many different ways are there to climb a staircase with n steps (for example, 100 steps) if you are allowed to skip steps, but not more than one at a time?
Explore by hand, look for a pattern:
n = 1:
1
n = 2:
1+1
2
n = 3:
1+1+1
1+2
2+1
1 way
2 ways
3 ways
n = 4:
1+1+1+1
1+1+2
1+2+1
2 +1+1
4 ways?
2+2
5 ways!
n = 5:
?
Too much work!
Use a computer:
Generate all sequences of 1s and 2s of length from 1 to n, and count the sequences for which the sum of the elements is equal to n.
Generate... – how?!
A better approach:
Model the situation in a different way (isomorphism):
0
1
0
0
0
1
0
0 marks a step we step on; 1 marks a step we skip.
A valid path cannot have two 1s in a row, ends with a 0.
Binary number system
for x in range (2**n): # Binary digits of x are used as a # sequence of 0s and 1s of length n
Bitwise logical operators
if x & (x << 1) == 0: # If the binary representation of x# has no two 1s in a row...
00010100010 00101100100 00101000100 01011001000 ------------------ ------------------ 00000000000 00001000000
Problem restated: Count all sequences of 0s and 1s of length n with no two 1s in a row
& &
def countPaths(n): """ Returns the number of sequences of 0s and 1s of length n with no two 1s in a row """ count = 0 for x in range(2**n): if x & (x << 1) == 0: count += 1 return count
for n in range(101): print(n+1, countPaths(n))
1 12 23 34 55 86 13...100 573147844013817084101
Fibonacci numbers!
Finalprogram:
def fibonacciList (n): "Returns the list of the first n Fibonacci numbers" fibs = [1, 1] while len(fibs) < n: fibs.append (fibs[-1] + fibs[-2]) return fibs
print (fibonacciList (101))
[1, 1, 2, 3, 5, 8, 13, ...,...... 573147844013817084101]
The answer is 101th Fibonacci number!
There is an easier way to compute it, of course, for example:
Back to math:
Show mathematically that the number of paths for n steps is the (n+1)th Fibonacci number.