Breaking

Thursday 8 June 2017

Ways to repay Loan


                        Ways to repay Loan


                                 Image result for c++


A poor man borrows a sum of N rupees from his neighbour.
 The neighbour is kind enough not to impose any interest on the loan.
The poor man agrees to re-pay the loan by paying back either 1 rupee or 2 rupees to his neighbour. In how many distinct ways can he repay the loan?

Input Format:The first line will contain the value of N which is the loan amount.

Output Format:The first line will contain the number of distinct ways in which the loan can be repaid.Constraints:1 <= N <= 999999

Example Input/Output 1:
Input:
1
Output:
1

Example Input/Output 2:
Input:
2
Output:
2
Explanation:The loan can be re-paid as 1,1 or as 2

Example Input/Output 3:
Input:
5
Output:
8

Explanation:
The loan can be re-paid as
1,1,1,1,1 or
1,1,1,2 or
1,2,2 or
1,1,2,1 or
1,2,1,1 or
2,2,1 or
2,1,2 or
2,1,1,1

Code:

  1. #include <iostream>
  2. using namespace std;
  3. int main(int argc, char** argv)
  4. {
  5.     long n,a=0,b=1,c=0;
  6.     cin>>n;
  7.     if(n==1)
  8.         cout<<"1";
  9.     else{
  10.     for(int i=0;i<n;i++)
  11.         {
  12.             c=a+b;
  13.             a=b;
  14.             b=c;
  15.         }
  16.     cout<<c;
  17.     }

No comments:

Post a Comment

Like