Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a value n. Our task is to find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n.

Let's take an example to understand the problem,

Input : n= 5
Output : 0

Explanation

(51 + 52 + 53 + 54) mod 5
= (5 + 25 + 125 + 625) mod 5
= (780) mode 5 = 0

Solution Approach

A simple solution to the problem is by directly finding the value of the equation for the given value of N and then calculating its modulus with 5.

Example

Program to illustrate the working of our solution

#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;
}

Output

For N = 12, the value of (n^1 + n^2 + n^3 + n^4)%5 is 0

Another solution to the problem is by using mathematical formulation and generalisation of the function.

$\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)}$

For this equation we can derive that the value of f(n) % 5 can be either 0 or 4 based on the value of n.

if(n%5 == 1),
   f(n)%5 = 4
Else,
   f(n)%5 = 0

Example

Program to illustrate the working of our solution

#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;
}

Output

For N = 65, the value of (n^1 + n^2 + n^3 + n^4)%5 is 4
raja
Updated on 01-Feb-2022 07:26:40

Advertisements