为什么当我从语句检查中删除"+ mod"时,以下程序给出错误的答案。问题链接:https://www.codechef.com/problems/FFC219B

Why does the following program gives wrong answer when I remove "+ mod" from statement check . Problem link: https://www.codechef.com/problems/FFC219B

本文关键字:链接 问题 错误 答案 https problems FFC219B com codechef www 出错      更新时间:2023-10-16

语句检查是我不明白为什么当我写"sum = (solution[R]-solution[L-1](%mod;"时它在提交时显示错误的答案。在这里我没有在括号内添加 mod。我不明白答案如何通过添加取相同模组的值来改变。代码厨师中的问题代码:https://www.codechef.com/problems/FFC219B

#include<iostream>
#define ll long long
#define mod 1000000007   //the modulus we need to take for the final answer
#define endl "n"
using namespace std;
long long solution[100007] = {0}; //Initialising all the values with zero
int main(){
ios_base :: sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution[0] = 0;
ll a1=1,a2=2,a3=3,a4=4;    //The variable initialising as per the problem
for(int i = 1;i <= 100007;i++){
ll k=(a1 * a2) % mod * a3 % mod * a4 % mod;
solution[i] = (solution[i-1]+k)%mod;  //Adding the previous values as we are to find the sum in range
a1++;
a2++;
a3++;
a4++;
}
int t; //Taking input for number of test cases
cin>>t;
while(t-->0)
{
int L,R;
cin>>L>>R; //Taking the range input
long long sum = 0;
sum = (solution[R]-solution[L-1] + mod)%mod; //statement check & final answer
cout<<sum<<endl;
}
return 0;
}

程序可以给出不正确的答案,因为正确答案必须始终是正数,而不是负数。

当你减去连续的模值时,即使数字本身在增加,结果也可能是负数(例如,(4^3(%10 - (4^2(%10 = 64%10 - 16%10 = 4-6 = -2(,。 这意味着"溶液[R]-溶液[L-1]"也可能是负面的,这意味着"(溶液[R]-溶液[L-1](%mod"也将是负面的 - 尽管显然答案(受影响的人数(必须始终是肯定的。

因此,以这种方式添加 mod 值可确保结果始终是积极的。