在 C++ 中,给定 n,求 (n^1 + n^2 + n^3 + n^4) mod 5 的值。
在这个问题中,我们给定一个值 n。我们的任务是*找到给定 n 的 (n^1 + n^2 + n^3 + n^4) mod 5 的值*。
让我们举个例子来理解这个问题,
Input : n= 5 Output : 0
**解释** -
(51 + 52 + 53 + 54) mod 5 = (5 + 25 + 125 + 625) mod 5 = (780) mode 5 = 0
解决方法
解决这个问题的一个简单方法是直接根据给定的 N 值计算方程的值,然后计算其对 5 的模。
示例
程序说明我们解决方案的工作原理
#include <iostream>
using namespace std;
int findMod5Val(int n){
int val = (n + (n*n) + (n*n*n) + (n*n*n*n));
return val%5;
}
int main(){
int n = 12;
cout<<"For N = "<<n<<", the value of (n^1 + n^2 + n^3 + n^4)\%5 is "<<findMod5Val(n);
return 0;
}输出
For N = 12, the value of (n^1 + n^2 + n^3 + n^4)%5 is 0
解决这个问题的另一种方法是使用数学公式和函数的泛化。
$\mathrm{f(n)\:=\:(n\:+\:n^2\:+\:n^3\:+\:n^4)}$
$\mathrm{f(n)\:=\:n^*(1\:+\:n\:+\:n^2\:+\:n^3)}$
$\mathrm{f(n)\:=\:n^*(1^*(1+n)+n^{2*}(1+n))}$
$\mathrm{f(n)\:=\:n^*((1+n^2)^*(1+n))}$
$\mathrm{f(n)\:=\:n^*(n+1)^*(n^2+1)}$
对于这个等式,我们可以推导出 f(n) % 5 的值基于 n 的值可以是 0 或 4。
if(n%5 == 1), f(n)%5 = 4 Else, f(n)%5 = 0
示例
程序说明我们解决方案的工作原理
#include <iostream>
using namespace std;
int findMod5Val(int n){
if(n % 4 == 1)
return 4;
return 0;
}
int main(){
int n = 65;
cout<<"For N = "<<n<<", the value of (n^1 + n^2 + n^3 + n^4)\%5 is "<<findMod5Val(n);
return 0;
}输出
For N = 65, the value of (n^1 + n^2 + n^3 + n^4)%5 is 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP