Advertisement
Guest User

Untitled

a guest
Jan 7th, 2015
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3. import java.math.*;
  4.  
  5. public class Main {
  6.  
  7. static BigInteger[][] PowMod(BigInteger[][] matr, long power, long modulo) {
  8. if (power == 1) {
  9. return matr;
  10. } else {
  11. BigInteger[][] matrOne = PowMod(matr, power / 2, modulo);
  12. BigInteger[][] matrTwo = new BigInteger[2][2];
  13. for (int i=0; i<2; i++) {
  14. for (int j=0; j<2; j++) {
  15. matrTwo[i][j] = matrOne[i][j];
  16. }
  17. }
  18. if (power % 2 != 0) {
  19. BigInteger[][] matrTemp = new BigInteger[2][2];
  20. for (int i=0; i<2; i++) {
  21. for (int j=0; j<2; j++) {
  22. matrTemp[i][j] = matrOne[i][j];
  23. }
  24. }
  25. for (int i=0; i<2; i++) {
  26. for (int j=0; j<2; j++) {
  27. matrTwo[i][j] = BigInteger.ZERO;
  28. for (int k=0; k<2; k++) {
  29. matrTwo[i][j] = matrTwo[i][j].add(matrTemp[i][k].multiply(matr[k][j]));
  30. }
  31. matrTwo[i][j] = matrTwo[i][j].mod(BigInteger.valueOf(modulo));
  32. }
  33. }
  34. }
  35.  
  36. BigInteger[][] matrRes = new BigInteger[2][2];
  37. for (int i=0; i<2; i++) {
  38. for (int j=0; j<2; j++) {
  39. matrRes[i][j] = BigInteger.ZERO;
  40. }
  41. }
  42. for (int i=0; i<2; i++) {
  43. for (int j=0; j<2; j++) {
  44. for (int k=0; k<2; k++) {
  45. matrRes[i][j] = matrRes[i][j].add(matrOne[i][k].multiply(matrTwo[k][j]));
  46. }
  47. matrRes[i][j] = matrRes[i][j].mod(BigInteger.valueOf(modulo));
  48. }
  49. }
  50. return matrRes;
  51. }
  52. }
  53.  
  54. public static void main(String[] args) throws IOException
  55. {
  56. Scanner in = new Scanner(System.in);
  57. long N=in.nextLong();
  58. long K=in.nextLong();
  59. long M=in.nextLong();
  60. BigInteger matr[][] = new BigInteger[2][2];
  61. matr[0][0] = BigInteger.ZERO;
  62. matr[1][0] = BigInteger.ONE;
  63. matr[0][1] = BigInteger.valueOf(K-1).mod(BigInteger.valueOf(M));
  64. matr[1][1] = BigInteger.valueOf(K-1).mod(BigInteger.valueOf(M));
  65.  
  66. BigInteger matrRes[][] = PowMod(matr, N - 1, M);
  67. BigInteger ans = matrRes[1][0].add(matrRes[1][1]);
  68. ans=ans.multiply(BigInteger.valueOf(K-1));
  69. ans=ans.mod(BigInteger.valueOf(M));
  70. System.out.println(ans);
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement