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