Find nth Hermite number in C++


In this problem, we are given an integer value N. Our task is to create a program to Find nth Hermite number.

Hermite Number is a number is the value of hermite number when there are 0 arguments.

Nth hermite Number is HN = (-2) * (N - 1) * H(N-2)
The base values are H0 = 1 and H0 = 0.

The hermite sequence is − 1, 0, -2, 0, 12, 0, -120, 0, 1680, 0….

Let’s take an example to understand the problem,

Input

N = 7

Output

0

Input

N = 6

Output

-120

Solution Approach

A simple solution to the problem is using the formula for hermite number. This is done using recursion, we can find Nth Term.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcNHermiteNumber(int N) {
   if (N == 0)
      return 1;
   if (N % 2 == 1)
      return 0;
   else
      return -2 * (N - 1) * calcNHermiteNumber(N - 2);
}
int main() {
   int N = 10;
   cout<<"The "<<N<<"th hermite Number is "<<calcNHermiteNumber(N);
   return 0;
}

Output

The 10th hermite Number is -30240

Efficient approach

An efficient approach to solve the problem is by using the formula. We can derive the general formula using the recursive formula.

Here, if the value of N is odd, the hermite number is 0.

If the value of N is even, their will be some value defined by the formula,

HN = ( (-1)(N/2)) * ( 2(N/2) ) * (N-1)!!

The (N-1)!! Is semi-factorial which is calculated as (n-1)*(n-3)*...3*1.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int calcSemiFact(int n) {
   int factVal = 1;
   for (int i = 1; i <= n; i = i + 2) {
      factVal *= i;
   }
   return factVal;
}
int calcNHermiteNumber(int n) {
   if (n % 2 == 1)
      return 0;
   int HermiteNumber = (pow(2, n / 2)) * calcSemiFact(n - 1);
   if ((n / 2) % 2 == 1)
      HermiteNumber *= -1;
   return HermiteNumber;
}
int main() {
   int N = 10;
   cout<<"The "<<N<<"th hermite Number is "<<calcNHermiteNumber(N);
   return 0;
}

Output

The 10th hermite Number is -30240

Updated on: 13-Mar-2021

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements