简体   繁体   English

如何使用模 10^9+7

[英]How to use modulo 10^9+7

I am trying to write a code for sum of square of natural numbers but with mod it's giving wrong answer.我正在尝试编写自然数平方和的代码,但是使用 mod 它给出了错误的答案。 What would be the correct way here?这里的正确方法是什么?

#include <bits/stdc++.h>
using namespace std;
#define mod 1000000007

int main()
{
    int N;
    cin>>N;
    cout<< (((N) * (N+1) * (2*N+1))/6)%mod;

    return 0;
}

(N) * (N+1) * (2*N+1) can be, even if N is less than 1000000007, too large. (N) * (N+1) * (2*N+1)可能,即使N小于 1000000007,也可能太大。 Namely up to 2000000039000000253000000546, which is an 91-bit number.即高达2000000039000000253000000546,这是一个91位的数字。 It is not likely that int on your system is capable of containing such large numbers.您系统上的int不太可能包含如此大的数字。

As usual with this type of question, the work-around is a combination of:与此类问题一样,解决方法是:

  • Using a larger integer type for intermediate products, and对中间产品使用更大的 integer 类型,以及
  • Applying modulo reduction on intermediate products, not only at the end.对中间产品应用模数减少,不仅在最后。

Using just one of them is not sufficient.仅使用其中之一是不够的。

As a consequence of applying modulo reduction earlier, the division by 6 will not work with a normal division, it will have to be a multiplication by the modular multiplicative inverse of 6 mod 1000000007, which is 166666668.由于之前应用了模减少,除以 6 将不适用于正常除法,它必须是乘以 6 mod 1000000007 的模乘逆,即 166666668。

Example code:示例代码:

mod_mul(mod_mul(mod_mul(N, N + 1, mod), mod_mul(2, N, mod) + 1, mod), inv6, mod)

Using some suitable definition of mod_mul , which can avoid overflow by using long long or a similar type.使用一些合适的mod_mul定义,可以通过使用long long或类似类型来避免溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM