递归计算函数f = n!/(c^n)的值

Recursively calculating the value of the function f = n!/(c^n)

本文关键字:的值 函数 递归计算      更新时间:2023-10-16

我在上周的测试中得到了这个问题:

/* Task 1: Implement the following function for calculating the value of
       the function f = n!/(c^n).
*/
float func(int n, int c) {
}

我试图在事实之后立即找出答案,因为这是我在测试过程中无法锻炼的事情(递归是我挣扎的事情)。

这是我到目前为止的尝试:

float result = 0;
// n!*c^n-1
float func( int n, int c )
{
    if( n == 0 )
       return result;
    result += n*c;
    return func( n*n-1, pow(c,-n) );
}

如果有人能帮助我解决这个问题,将不胜感激。谢谢大家!

    float result = 1;
// n!*c^n-1
float func( double n, double c )
{
    if( n == 0 )
       return result;
    return func(n-1,c )*(n/c);
}

这是用于解决此问题的算法我将函数的参数从int更改为两倍,因为最后一行包含(n/c),而整数偏差会导致错误的答案,如果c不是n

的除数

您应该注意到f(n,c) =f(n-1,c)*(n/c),因为n!=n*(n-1)!