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] = 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
Updated on: 2019-12-19T10:31:16+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements