Count the number of ways to reach Nth stair by taking jumps of 1 to N
Given an integer N which depicts the number of stairs, the task is to count the number of ways to reach Nth stair by taking jumps of 1 to N.
Examples:
Input: N = 2
Output: 2
Explanation: Two ways to reach are: (1, 1) & (2)
Input: N = 3
Output: 4
Input: N = 4
Output: 8
Approach: In this problem, the number of ways to reach the ith stair is:
Ways to reach ith stair = (Sum of ways to reach stairs 1 to i-1)+1
As for any stair before i, ith stair can be reached in a single jump. And +1 for jumping directly to i.
Now to solve this problem:
- Create a variable sum to store the number of ways to reach on a particular stair. Initialise it with 0.
- Run a loop from i=1 to i=N-1 and for each iteration:
- Create a variable, say cur to store the number of ways to the current stair. So, cur = sum + 1.
- Change sum to sum = sum + cur.
- Return sum + 1 after the loop ends as the answer to this problem.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findWays( int N)
{
int sum = 0;
for ( int i = 1; i < N; i++) {
int cur = sum + 1;
sum += cur;
}
return sum + 1;
}
int main()
{
int N = 10;
cout << findWays(N);
}
|
Java
import java.util.*;
public class GFG
{
static int findWays( int N)
{
int sum = 0 ;
for ( int i = 1 ; i < N; i++) {
int cur = sum + 1 ;
sum += cur;
}
return sum + 1 ;
}
public static void main(String args[])
{
int N = 10 ;
System.out.print(findWays(N));
}
}
|
Python3
def findWays(N):
sum = 0
for i in range ( 1 , N):
cur = sum + 1
sum + = cur
return sum + 1
if __name__ = = "__main__" :
N = 10
print (findWays(N))
|
C#
using System;
class GFG
{
static int findWays( int N)
{
int sum = 0;
for ( int i = 1; i < N; i++) {
int cur = sum + 1;
sum += cur;
}
return sum + 1;
}
public static void Main()
{
int N = 10;
Console.Write(findWays(N));
}
}
|
Javascript
<script>
function findWays(N) {
let sum = 0;
for (let i = 1; i < N; i++) {
let cur = sum + 1;
sum += cur;
}
return sum + 1;
}
let N = 10;
document.write(findWays(N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
10 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...