在计算阶乘之前可以知道阶乘有多大吗?

发布于 2024-07-26 22:10:38 字数 73 浏览 3 评论 0原文

我正在使用 GMP 来计算非常大的阶乘(例如 234234!)。 在进行计算之前,有什么方法可以知道结果将(或可能)有多少位数字?

I'm using GMP to calculate very large factorials (e.g. 234234!). Is there any way of knowing, before one does the calculation, how many digits long the result will (or might) be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

江南烟雨〆相思醉 2024-08-02 22:10:38

您可以使用简单的对数数学转换斯特林近似公式来获得位数:

n!         ~ sqr(2*pi*n) * (n/e)^n
log10(n!)  ~ log10(2*pi*n)/2 + n*log10(n/e)

硬件浮点数学足以满足这一点,这使得它快如闪电。

You can transform Stirling's approximation formula using simple logarithmic math to get you the number of digits:

n!         ~ sqr(2*pi*n) * (n/e)^n
log10(n!)  ~ log10(2*pi*n)/2 + n*log10(n/e)

Hardware float math is sufficient for this, which makes it lightning fast.

又爬满兰若 2024-08-02 22:10:38

阶乘的对数可用于计算阶乘数所需的位数:

logn!

这可以很容易地转换为算法形式:

//Pseudo-code
function factorialDigits (n) 
  var result = 0;

  for(i = 1; i<=n; i++)
    result += log10(n);

  return result;

The logarithm of the factorial can be used to calculate the number of digits that the factorial number will take:

logn!

This can be easily translated to an algorithmic form:

//Pseudo-code
function factorialDigits (n) 
  var result = 0;

  for(i = 1; i<=n; i++)
    result += log10(n);

  return result;
情话已封尘 2024-08-02 22:10:38

斯特林近似给出了 n 大小的近似值!

alt text

请参阅 维基百科 推导页面。

Stirling's Approximation gives an approximation of of the size of n!

alt text

See the Wikipedia page for the derivation.

┼── 2024-08-02 22:10:38

它将

nlog(n) - n + log(n(1 + 4n(1 + 2n)))/6 + log(pi)/2

看到主题“增长率”@ http://en.wikipedia.org/wiki/Factorial
斯里尼瓦萨·拉马努金方法

it would be

nlog(n) - n + log(n(1 + 4n(1 + 2n)))/6 + log(pi)/2

see topic "rate of growth" @ http://en.wikipedia.org/wiki/Factorial
Srinivasa Ramanujan method

人海汹涌 2024-08-02 22:10:38

是的,请参阅斯特林近似

它说n! ~= sqrt(2*Pin)(n/e)^n。 要获得位数,请取 1+log(n!)/log(10)。

Yes, see Stirling approximation

It says n! ~= sqrt(2*Pin)(n/e)^n. To get the number of digits, take 1+log(n!)/log(10).

你不是我要的菜∠ 2024-08-02 22:10:38

大约有四个人提到过斯特林,所以...另一种选择是使用 LUT 存储前 N 个阶乘中每个阶乘的位数。 假设整数有 4 个字节,位数有 4 个字节,则可以将前 1,000,000 个阶乘存储在大约 8MB 中。

Well about four people have mentioned Stirling so... another option is a LUT storing the number of digits for each of the first N factorials. Assuming 4 bytes for the integer and 4 bytes for the number of digits, you could store the first 1,000,000 factorials in around 8MB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文