Program to find number of ways we can reach to the next floor using stairs in Python

PythonServer Side ProgrammingProgramming

Suppose there is a stair case with N steps. One can either go step by step, or at each step, one can take a jump of at most N steps. We have to find the number of ways in which we can go to the top floor. The N value may be large we are only interested in the first and the last K digits of number of ways.

So, if the input is like N = 10 k = 2, then the output will be 63 because there are 10 steps, if there are S number of ways in which we can go to the top, then consider S be of the form wxyz.So, summing wx + yz is 63.

To solve this, we will follow these steps −

  • N := N - 1
  • c := 2 * ceiling of (k + log(N);base10)
  • e := N, b := 2, s := 1
  • while e > 0, do
    • if e is odd, then
      • s := the first p-c digit numbers of (s*b) where p is number of digits in s*b
    • e := floor of e/2
    • b := the first p-c digit numbers of (b*b) where p is number of digits in b*b
  • s := first p - k digit number of s, where p is number of digits in s
  • r := s + (2^N) mod 10^k
  • return r

Example

Let us see the following implementation to get better understanding −

from math import log10,ceil

def solve(N,k):
   N -= 1
   c = 2*ceil(k + log10(N))
   e = N
   b = 2
   s = 1
   while e > 0:
      if e % 2 == 1:
         s = int(str(s*b)[:c])
      e //=2
      b = int(str(b*b)[:c])
   s = str(s)[:k]
   r = int(s) + pow(2, N, 10**k)
   return r

N = 10
k = 2
print(solve(N,k))

Input

10, 2

Output

63
raja
Updated on 25-Oct-2021 06:50:10

Advertisements