在C++中查找第n个厄米特数


在这个问题中,我们给定一个整数N。我们的任务是创建一个程序来查找第n个厄米特数。

厄米特数是在参数为0时的厄米特多项式的值。

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

厄米特数列为:-1, 0, -2, 0, 12, 0, -120, 0, 1680, 0…

让我们举个例子来理解这个问题:

输入

N = 7

输出

0

输入

N = 6

输出

-120

解决方案

解决这个问题的一个简单方法是使用厄米特数的公式。通过递归,我们可以找到第N项。

程序演示了我们解决方案的工作原理:

示例

在线演示

#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;
}

输出

The 10th hermite Number is -30240

高效方法

解决这个问题的高效方法是使用公式。我们可以使用递归公式推导出一般公式。

这里,如果N的值是奇数,则厄米特数为0。

如果N的值是偶数,则其值由公式定义:

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

(N-1)!! 是半阶乘,计算方法为 (n-1)*(n-3)*...*3*1。

程序演示了我们解决方案的工作原理:

示例

在线演示

#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;
}

输出

The 10th hermite Number is -30240

更新于:2021年3月13日

83 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.