“计算n!"后面的数学运算!在模p"下?

编程入门 行业动态 更新时间:2024-10-27 12:39:24
本文介绍了“计算n!"后面的数学运算!在模p"下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

long long x; for (int i = 1; i <= n; i++) { x = (x * i) % m; } cout << x;

这是计算(n!)mod m的技巧(假设m> n).但是,我不知道为什么这是真的.您能解释一下其背后的数学机制吗?

解决方案

此处的基本思想是,您可以在乘法之前,期间或之后获取模数,并在获取最终结果的模数后获得相同的值. /p>

@Peter指出,

(a * b) % m == ((a % m) * (b % m)) % m

对于阶乘,

n! = 1 * 2 * 3 * ... * (n-1) * n

所以我们有

n! % m = (((((((1 * 2) % m) * 3) % m) * ... * n-1) % m) * n) % m

每次迭代后取模.

这样做的好处是您的数字不会爆炸并溢出您的long long类型,就像不使用中间模数值那样很快.

long long x; for (int i = 1; i <= n; i++) { x = (x * i) % m; } cout << x;

This is the trick to calculate (n!) mod m (assume m > n). However, I don't know why it's true. Can you explain the math mechanism behind this?

解决方案

The basic idea here is that you can take the modulus before, during, or after multiplication and get the same value after taking the modulus of the final result.

As @Peter points out,

(a * b) % m == ((a % m) * (b % m)) % m

For the factorial,

n! = 1 * 2 * 3 * ... * (n-1) * n

so we have

n! % m = (((((((1 * 2) % m) * 3) % m) * ... * n-1) % m) * n) % m

taking the modulus after each iteration.

The advantage to doing it this way is that your number won't blow up and overflow your long long type like it would do pretty quickly if you didn't take intermediate modulus values.

更多推荐

“计算n!"后面的数学运算!在模p"下?

本文发布于:2023-10-24 09:02:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523516.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数学   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!