Sequence#1083

Sequence (Editorial)

Let us express the first terms of the sequence in terms of a_1:

Thus, the formula can be written as:

a_i = a_{i-1}^2~mod~10000

Which means that to compute a_n, it is enough to raise a_1 to the power of 2^{n - 1} modulo :

a_n = a_1^{2^{n-1}}~mod~10000

Taking into account the modular exponentiation identity:

a^b~mod~n = a^{b~mod~\phi(n)}~mod~n,

we proceed as follows to find the result :

Algorithm implementation

The function PowMod computes the value of x^n~mod~m.

int PowMod(int x, int n, int m)
{
  if (n == 0) return 1;
  if (n % 2 == 0) return PowMod((x * x) % m, n / 2, m);
  return (x * PowMod(x, n - 1, m)) % m;
}

Read the input data.

scanf("%d %d",&a,&n);

Compute x = 2^{n - 1}~mod~4000. And after that, compute and print the final answer:

res = a^x~mod~10000
x = PowMod(2,n-1,4000);
res = PowMod(a,x,10000);
printf("%d\n",res);

Java implementation

import java.util.*;

public class Main
{
  static long PowMod(long x, long n, long m)
  {
    if (n == 0) return 1;
    if (n % 2 == 0) return PowMod((x * x) % m, n / 2, m);
    return (x * PowMod(x, n - 1, m)) % m;
  }

  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    long a = con.nextLong();
    long n = con.nextLong();
    long x = PowMod(2,n-1,4000);
    long res = PowMod(a,x,10000);
    System.out.println(res);
    con.close();
  }
}