# Find (1^n + 2^n + 3^n + 4^n) mod 5 in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to solve the following problem.

Given an integer n, we have to find the (1n+2n+3n+4n)%5

The number (1n+2n+3n+4n) will be very large if n is large. It can't be fit in the long integers as well. So, we need to find an alternate solution.

If you solve the equation for the number 1, 2, 3, 4, 5, 6, 7, 8, 9 you will get 10, 30, 100, 354, 1300, 4890, 18700, 72354, 282340 values respectively.

Observe the results of the equation carefully. You will find that the last digit of the equation result repeats for every 4th number. It's the periodicity of the equation.

Without actually calculating the equation we can say that the

if n%4==0﻿ then (1n+2n+3n+4n)%5 will be 4 else 0.

## Example

Let's see the code.

Live Demo

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

## Output

If you run the above code, then you will get the following result.

0

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.