# 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

Live Demo

#include<iostream>
using namespace std;
int findTerm(int n) {
int table[n+1];
table = 0;
table = 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