In a sequence of numbers
a1, a2,
a3,
... the
first term is given, and the other terms are calculated using the formula:
ai = (ai-1
* ai-1) mod
10000
Find the n-th
term of the sequence.
Input. The first row contains the
numbers a1 and n (0 ≤ a1 ≤ 10000, 1 ≤ n ≤ 2000000010).
Output. Print the value of an.
Sample input |
Sample output |
4 3 |
256 |
exponentiation
Let us express
the first terms of the
sequence in terms of a1:
·
a2 =
a12 mod 10000,
·
a3 =
a22 mod 10000 =
a14 mod 10000,
·
a4 =
a32 mod 10000 =
a24 mod 10000 =
a18 mod 10000
The formula can
be rewritten as ai = ai-12
mod 10000, whence it follows that to calculate an, the number a1 should be raised to the power 2n–1:
Considering that ab mod n = ab
mod j(n) mod n, to find the result res,
the following calculations should be performed:
x = 2n–1 mod j(10000) =
2n–1 mod 4000,
res = a1x mod 10000
Function PowMod finds the value of
xn 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);
First
find the value of x = 2n–1 mod 4000, and then find and print the answer
res = ax mod 10000
x
= PowMod(2,n-1,4000);
res
= PowMod(a,x,10000);
printf("%d\n",res);
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();
}
}