- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Motzkin number in C++
The Motzkin number series starts with 1, 1, 4, 9, etc.., We can get the generalised nth term with the sequence. The Motzkin number sequence is as follows.
a0 = 1
a1 = 1
a2 = 4
a3 = 9
an = ((2 * n + 1)/ n + 2) * M(n-1) +((3 * n - 3)/ n + 2) * M(n - 2)
Algorithm
Initialise the number n.
Iterate till n.
Update the previous two numbers
Return the last number.
Example
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int getNthTerm(int n) { if(n == 0 || n == 1) { return 1; } int a = 1, b = 1; for(int i = 2; i <= n; ++i) { int c = ((2 * i + 1) * b + (3 * i - 3) * a) / (i + 2); a = b; b = c; } return b; } int main() { int n = 5; cout << getNthTerm(n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
21
Advertisements