在C ++中使用负数的模数 [英] Modulus with negative numbers in C++
本文介绍了在C ++中使用负数的模数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经为以下递归关系编写程序:
I have been writing a program for the following recurrence relation:
An = 5An-1 - 2An-2 - An-3 + An-4
输出应为答案模数10 ^ 9 + 7 ..
我写了一个强力的方法,如下:
The output should be the Answer modulus 10^9 + 7.. I wrote a brute force approach for this one as follows...
long long int t1=5, t2=9, t3=11, t4=13, sum;
while(i--)
{
sum=((5*t4) - 2*t3 - t2 +t1)%MOD;
t1=t2;
t2=t3;
t3=t4;
t4=sum;
}
printf("%lld\n", sum);
其中 MOD = 10 ^ 9 +7
每一件事情似乎是真的..但我得到一些值的负面答案..和由于这个问题,我找不到正确的解决方案...
Plz帮助正确的地方保持 Modulus
推荐答案
bb
(a/b)*b + a%b == a (for b!=0)
(从C99和C ++ 11,我认为),-5/4将是-1,我们有
So, if in case your integer division rounds towards zero (which is mandated since C99 and C++11, I think), -5/4 will be -1 and we have
(-5/4)*4 + -5%4 == -5
-1 *4 -1 == -5
为了得到一个正数结果(对于模操作),你需要添加除数,以便余数为负或做这样的事情:
In order to get a positive result (for the modulo operation) you need to add the divisor in case the remainder was negative or do something like this:
long mod(long a, long b)
{ return (a%b+b)%b; }
这篇关于在C ++中使用负数的模数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文