
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find n-th element from Stern’s Diatomic Series in C++
Here we will see how to find the nth term in Stern’s Diatomic series. The series is like 0, 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4, … This is also known as fusc function. This series can be defined as −
𝑝(𝑛)=$p\lgroup\frac{n}{2}\rgroup$ 𝑤ℎ𝑒𝑛 𝑛 𝑖𝑠 𝑒𝑣𝑒𝑛
𝑝(𝑛)=$p\lgroup\frac{n-1}{2}\rgroup+p\lgroup\frac{n+1}{2}\rgroup$ 𝑤ℎ𝑒𝑛 𝑛 𝑖𝑠 𝑜𝑑𝑑
𝑝(0)=0 𝑎𝑛𝑑 𝑝(1)=1
Here we will use the Dynamic programming approach to reduce the number of computations. After saving the base case for p(0) and p(1), we will iterate from index i = 2 to n, and compute p(i)
Example
#include<iostream> using namespace std; int findTerm(int n) { int table[n+1]; table[0] = 0; table[1] = 1; for (int i = 2; i <= n; i++) { if (i % 2 == 0) table[i] = table[i / 2]; else table[i] = table[(i - 1) / 2] + table[(i + 1) / 2]; } return table[n]; } int main() { cout << 3 << " rd term is: " << findTerm(3) << endl; cout << 15 << " th term is: " << findTerm(15) << endl; cout << 20 << " th term is: " << findTerm(20) << endl; }
Output
3 rd term is: 2 15 th term is: 4 20 th term is: 3
- Related Articles
- Find n-th element in a series with only 2 digits (and 7) allowed in C++
- Program to find N-th term in the given series in C++
- Find k-th smallest element in given n ranges in C++
- Find sum of Series with n-th term as n^2 - (n-1)^2 in C++
- C++ program to find n-th term in the series 7, 15, 32, …
- C++ program to find n-th term in the series 9, 33, 73,129 …
- Program to find N-th term of series a, b, b, c, c, c…in C++
- Program to find N-th term of series 3, 6, 18, 24, … in C++
- n-th term of series 1, 17, 98, 354…… in C++
- Program to find N-th term of series 3, 5, 33, 35, 53… in C++
- Program to find N-th term of series 1, 2, 11, 12, 21… in C++
- Program to find N-th term of series 1, 3, 12, 60, 360...in C++
- Program to find N-th term of series 2, 4, 3, 4, 15… in C++
- Program to find N-th term of series 3 , 5 , 21 , 51 , 95 , … in C++
- Program to find N-th term of series 3, 12, 29, 54, 87, … in C++

Advertisements