在 C++ 中求 (1^n + 2^n + 3^n + 4^n) mod 5


在本教程中,我们将解决以下问题。

给定一个整数 n,我们必须找到 (1n+2n+3n+4n)%5

如果 n 很大,则数字 (1n+2n+3n+4n) 将非常大。它也不能放入长整数中。因此,我们需要找到一个替代解决方案。

如果您针对数字 1、2、3、4、5、6、7、8、9 求解方程,您将分别得到 10、30、100、354、1300、4890、18700、72354、282340 的值。

仔细观察方程结果。您会发现方程结果的最后一位数字每隔 4 个数字就会重复一次。这是方程的周期性。

无需实际计算方程,我们可以说

如果 n%4==0,则 (1n+2n+3n+4n)%5 将为 4,否则为 0

示例

让我们看看代码。

 实时演示

#include <bits/stdc++.h>
using namespace std;
int findSequenceMod5(int n) {
   return (n % 4) ? 0 : 4;
}
int main() {
   int n = 343;
   cout << findSequenceMod5(n) << endl;
   return 0;
}

输出

如果您运行以上代码,则将获得以下结果。

0

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

如果您在本教程中有任何疑问,请在评论区中提及。

更新于:2021 年 2 月 1 日

213 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告