
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Ways to Express N as the Sum of 1, 3, and 4 in C++
Given a positive number N as input. The goal is to find the number of ways in which we can express N as a sum of 1s, 3s and 4s only. For example, if N is 4 then it can be represented as 1+1+1+1, 3+1, 1+3, 4 so the number of ways will be 4.
Let us understand with examples.
For Example
Input - N=5
Output - Count of different ways to express N as the sum of 1, 3 and 4 are: 6
Explanation - 5 can be represented as:
- 1+1+1+1+1
- 1+3+1
- 3+1+1
- 1+1+3
- 4+1
- 1+4
Input - N=6
Output - Count of different ways to express N as the sum of 1, 3 and 4 are: 9
Explanation - 9 can be represented as:
- 1+1+1+1+1+1
- 3+1+1+1
- 1+3+1+1
- 1+1+3+1
- 1+1+1+3
- 3+3
- 4+1+1
- 1+4+1
- 1+1+4
Approach used in the below program is as follows
In this approach we will use a dynamic programming approach to count the number of ways we can represent N as sum of 1, 3 and 4. Take array arr[i] where i represents the number and arr[i] as ways to represent it as sum.
The base cases will be
arr[0]=0 ( No way )
arr[1]=1 ( only one way , 1 )
arr[2]=1 ( only one way, 1+1 )
arr[3]=2 ( 1+1+1, 3 )
Now other numbers 4, 5 … i etc. will have ways as arr[i-1]+arr[i-3]+arr[i-4].
- Take a positive number N as input.
- Function Expres_sum(int N) takes N and returns the count of different ways to express N as the sum of 1, 3 and 4.
- Take array arr[N+1] to store the count of ways.
- Initialize base cases arr[0] = 1, arr[1] = 1, arr[2] = 1 and arr[3] = 2.
- Traverse for rest of the values from i=4 to i<=N.
- Takeaways arr[i] as sum of arr[i - 1] + arr[i - 3] + arr[i - 4].
- At the end of the for loop return arr[N] as result.
Example
#include <bits/stdc++.h> using namespace std; int Expres_sum(int N) { int arr[N + 1]; arr[0] = 1; arr[1] = 1; arr[2] = 1; arr[3] = 2; for (int i = 4; i <= N; i++) { arr[i] = arr[i - 1] + arr[i - 3] + arr[i - 4]; } return arr[N]; } int main() { int N = 5; cout << "Count of different ways to express N as the sum of 1, 3 and 4 are: " << Expres_sum(N); return 0; }
If we run the above code it will generate the following output −
Output
Count of different ways to express N as the sum of 1, 3 and 4 are: 6