Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- import java.math.*;
- public class Main {
- static BigInteger[][] PowMod(BigInteger[][] matr, long power, long modulo) {
- if (power == 1) {
- return matr;
- } else {
- BigInteger[][] matrOne = PowMod(matr, power / 2, modulo);
- BigInteger[][] matrTwo = new BigInteger[2][2];
- for (int i=0; i<2; i++) {
- for (int j=0; j<2; j++) {
- matrTwo[i][j] = matrOne[i][j];
- }
- }
- if (power % 2 != 0) {
- BigInteger[][] matrTemp = new BigInteger[2][2];
- for (int i=0; i<2; i++) {
- for (int j=0; j<2; j++) {
- matrTemp[i][j] = matrOne[i][j];
- }
- }
- for (int i=0; i<2; i++) {
- for (int j=0; j<2; j++) {
- matrTwo[i][j] = BigInteger.ZERO;
- for (int k=0; k<2; k++) {
- matrTwo[i][j] = matrTwo[i][j].add(matrTemp[i][k].multiply(matr[k][j]));
- }
- matrTwo[i][j] = matrTwo[i][j].mod(BigInteger.valueOf(modulo));
- }
- }
- }
- BigInteger[][] matrRes = new BigInteger[2][2];
- for (int i=0; i<2; i++) {
- for (int j=0; j<2; j++) {
- matrRes[i][j] = BigInteger.ZERO;
- }
- }
- for (int i=0; i<2; i++) {
- for (int j=0; j<2; j++) {
- for (int k=0; k<2; k++) {
- matrRes[i][j] = matrRes[i][j].add(matrOne[i][k].multiply(matrTwo[k][j]));
- }
- matrRes[i][j] = matrRes[i][j].mod(BigInteger.valueOf(modulo));
- }
- }
- return matrRes;
- }
- }
- public static void main(String[] args) throws IOException
- {
- Scanner in = new Scanner(System.in);
- long N=in.nextLong();
- long K=in.nextLong();
- long M=in.nextLong();
- BigInteger matr[][] = new BigInteger[2][2];
- matr[0][0] = BigInteger.ZERO;
- matr[1][0] = BigInteger.ONE;
- matr[0][1] = BigInteger.valueOf(K-1).mod(BigInteger.valueOf(M));
- matr[1][1] = BigInteger.valueOf(K-1).mod(BigInteger.valueOf(M));
- BigInteger matrRes[][] = PowMod(matr, N - 1, M);
- BigInteger ans = matrRes[1][0].add(matrRes[1][1]);
- ans=ans.multiply(BigInteger.valueOf(K-1));
- ans=ans.mod(BigInteger.valueOf(M));
- System.out.println(ans);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement