fork(3) download
  1. // Calculate Nth Fibbionacci number in O(log N)
  2. import java.util.Scanner;
  3. object Main{
  4. // Matrix multiplication
  5. def matmul(mat1 : Array[ Array [Int] ], mat2 : Array[ Array [Int] ]): Array[ Array [Int] ] = {
  6. val n = mat1.size;
  7. var res = new Array[ Array [Int]](n, n);
  8. for(i <- 0 until n){
  9. for(j <- 0 until n){
  10. res(i)(j) = 0;
  11. for(k <- 0 until n){
  12. res(i)(j) += mat1(i)(k) * mat2(k)(j);
  13. }
  14. }
  15. }
  16. return res;
  17. }
  18. // Matrix powering
  19. def matpow(mat : Array[ Array [Int] ], p : Int): Array[ Array [Int] ] = {
  20. val n = mat.size;
  21. var pow = p;
  22. var par, res = new Array[ Array [Int]](n, n);
  23. for(i <- 0 until n){
  24. for(j <- 0 until n){
  25. par(i)(j) = mat(i)(j);
  26. if(i == j) res(i)(j) = 1;
  27. else res(i)(j) = 0;
  28. }
  29. }
  30. while(pow > 0){
  31. if(pow % 2 == 1){
  32. res = matmul(res, par);
  33. }
  34. par = matmul(par, par);
  35. pow /= 2;
  36. }
  37. return res;
  38. }
  39. // Calculate sum of a
  40. def fibb(n : Int): Int = {
  41. var mat = new Array[ Array [Int]](2, 2);
  42. mat(0)(0) = 1; mat(0)(1) = 1; mat(1)(0) = 1; mat(1)(1) = 0;
  43. mat = matpow(mat, n);
  44. return mat(1)(0);
  45. }
  46. // Main function
  47. def main(args : Array[ String ]) = {
  48. val in = new Scanner(System.in);
  49. val num = in.nextInt();
  50. println(fibb(num));
  51. }
  52. }
  53.  
Runtime error #stdin #stdout 0.04s 211456KB
stdin
Standard input is empty
stdout
Standard output is empty