Find the value of the function Y = (X^6 + X^2 + 9894845) % 981 in C++

C++Server Side ProgrammingProgramming

Suppose we have given function like f(x) = (x^6 + x^2 + 9894845) % 971, now for a given value of x, we have to find the value of f(x).

So, if the input is like 5, then the output will be 469

To solve this, we will follow these steps −

  • Define a function power_mod(), this will take base, exponent, modulus,

  • base := base mod modulus

  • result := 1

  • while exponent > 0, do −

    • if exponent is odd, then −

      • result := (result * base) mod modulus

    • base := (base * base) mod modulus

    • exponent = exponent /2

  • return result

  • From the main method do the following −

  • return power_mod(n, 6, m)+power_mod(n, 2, m)) mod m + 355) mod m

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
lli power_mod(lli base, lli exponent, lli modulus) {
   base %= modulus;
   lli result = 1;
   while (exponent > 0) {
      if (exponent & 1)
         result = (result * base) % modulus;
      base = (base * base) % modulus;
      exponent >>= 1;
   }
   return result;
}
int main(){
   lli n = 654654, m = 971;
   cout<<(((power_mod(n, 6, m)+power_mod(n, 2, m))% m + 355)% m);
}

Input

84562

Output

450
raja
Published on 27-Aug-2020 16:03:09
Advertisements