Search code examples
c++recursionfactoriallogarithm

Computing lg(N!): Anyone have a Better Recursive Method?


I think the title of the post addresses my question. But just to reiterate, I am wondering if anyone has a better approach to this problem.

/* Write a recursive program to compute lg( N! ) */

#include <iostream>

#include <cmath>

using namespace std;

long double log_base2( long double N ) {
    return log( N )/log( 2.0 );
}

long double lg_n_factorial( long N ) {
    if( 1 == N ) return log_base2( static_cast<long double>( N ) );
    else return lg_n_factorial( N -1 ) + log_base2( static_cast<long double>( N ) );
}

int main( int argc, char *argv[] ) {
    cout << ( lg_n_factorial( 10 ) ) << endl;
    return 0;
}

Based on people's responses, I should clarify, this is a problem out of a book, and the book says to do it recursivly. I am practicing programming problems, and trying to get feedback from others so I can catch my mistakes as I work on becoming a better programmer.


Solution

  • Just do it iteratively? I don't see a reason this problem needs to be solved recursively. If you have a requirement (For some reason or other) to do it recursively your way appears to work fine, although your base case can just be to return 0 (log(1) in any base is 0).

    Also, there's no need to convert to base 2 at each step: You can do it once at the end.