求一个数阶乘的位数

flyfish 2015-8-15

例如 7!=5040 ,7的阶乘结果是4位数(10进制)

求一个数的位数

1 循环方法

int get_digit_loop(int N)
 {
    int digit = 0;
    do
    {
        digit ++;
    } while ((N /= 10) > 0);
    return digit;
}

2 递归方式

int get_digit_recursion(int N)
{
    int digit = 0;
    digit = N < 10 ? 1 : 1 + get_digit_recursion(N/10);
    return digit;
}

3 math头文件自带的库函数

int get_digit_lib(int N)
{
    int digit = (floor) (log10(N)) + 1;
    return digit;
}

求一个数阶乘的位数
可以直接采用log10求一个数阶乘的位数
N=n!
方法1
log10(n!)
=log10(123n)
=log10(1)+log10(2)++log10(n)

log10N表示以10为底,N的对数。缩写是lgN.

natural logarithm 自然对数
natural 英 [‘nætʃ(ə)r(ə)l] 美 [‘nætʃrəl]
logarithm 英 [‘lɒgərɪð(ə)m; -rɪθ-] 美 [‘lɔɡərɪðəm]

方法2
利用斯特林公式
斯特灵公式
Stirling’s approximation
Stirling’s formula

Stirling 英 [‘stə:liŋ]
approximation 英 [ə,prɒksɪ’meɪʃn] 美 [ə’prɑksə’meʃən][数] 近似法;接近;[数] 近似值
formula 英 [‘fɔːmjʊlə] 美 [‘fɔrmjələ][数] 公式,准则;配方;婴儿食

log10(n!)
=log10(sqrt(2pin))+nlog10(n/e)

e 是(mathematical constant)数学常数
e 2.71828
以e为底的对数叫自然对数(Natural logarithm)
pi也是mathematical constant
Pi 3.14159265 圆周率
the ratio of a circle’s circumference to its diameter
圆的周长与直径的比值

int digit_stirling(int n)
{
    double PI=acos(double(-1));// PI的值=反余弦函数 -1.0为Pi, 1为0。
    double e=exp(double(1));//e的值
    return floor(log10(sqrt(2*PI*n))+n*log10(n/e))+1;
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐