Monday, 24 February 2014

UVA Problem ID 10229 (Modular Fibonacci)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
 public static void main (String args[]) throws IOException
 {
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String input;
  StringBuilder sb=new StringBuilder(1000);
  
  while((input=br.readLine())!=null)
  {
   String numbers[]=input.trim().split(" +");
   long matrixA[][]={{1,1},{1,0}};
   long ans=matrixpowerMod(matrixA,Integer.parseInt(numbers[0]),(int) Math.pow(2,Integer.parseInt(numbers[1])))[0][1];
   sb.append(ans+"\n");
  }
  System.out.print(sb);
 }
 public static long[][] matrixmultiplication(long[][] A,long[][] B,int mod)
 {
  long resultantmatrix[][]=new long[2][2];
  resultantmatrix[0][0] =  (A[0][0]*B[0][0] + A[0][1]*B[1][0]) % mod;
  resultantmatrix[0][1] =  (A[0][0]*B[0][1] + A[0][1]*B[1][1]) % mod;
  resultantmatrix[1][0] =  (A[1][0]*B[0][0] + A[1][1]*B[1][0] )% mod;
  resultantmatrix[1][1] =  (A[1][0]*B[0][1] + A[1][1]*B[1][1] )% mod;
  
  return resultantmatrix;
 }
 public static long[][] matrixpowerMod(long[][] A,long power,int mod)
 {
  if(power==0)
  {
   long matrixA[][]={{1,0},{0,1}};
   return matrixA;
  }
  
  else if(power % 2==0)
  {
   long C[][]=matrixpowerMod(A, power/2,mod);
   return matrixmultiplication(C,C,mod);
  }
  else
  {
   return matrixmultiplication(A,matrixpowerMod(A, power-1,mod),mod);
  }
 }
}

Previous Post
Next Post

0 comments:

Advertisement