Home > Backend Development > C++ > body text

In C++, Motzkin numbers

WBOY
Release: 2023-08-25 19:13:06
forward
1330 people have browsed it

In C++, Motzkin numbers

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;
}
Copy after login

输出

如果您运行上述代码,您将得到以下结果。

21
Copy after login

The above is the detailed content of In C++, Motzkin numbers. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!