1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | // Calculate Nth Fibbionacci number in O(log N) import java.util.Scanner; object Main{ // Matrix multiplication def matmul(mat1 : Array[ Array [Int] ], mat2 : Array[ Array [Int] ]): Array[ Array [Int] ] = { val n = mat1.size; var res = new Array[ Array [Int]](n, n); for(i <- 0 until n){ for(j <- 0 until n){ res(i)(j) = 0; for(k <- 0 until n){ res(i)(j) += mat1(i)(k) * mat2(k)(j); } } } return res; } // Matrix powering def matpow(mat : Array[ Array [Int] ], p : Int): Array[ Array [Int] ] = { val n = mat.size; var pow = p; var par, res = new Array[ Array [Int]](n, n); for(i <- 0 until n){ for(j <- 0 until n){ par(i)(j) = mat(i)(j); if(i == j) res(i)(j) = 1; else res(i)(j) = 0; } } while(pow > 0){ if(pow % 2 == 1){ res = matmul(res, par); } par = matmul(par, par); pow /= 2; } return res; } // Calculate sum of a def fibb(n : Int): Int = { var mat = new Array[ Array [Int]](2, 2); mat(0)(0) = 1; mat(0)(1) = 1; mat(1)(0) = 1; mat(1)(1) = 0; mat = matpow(mat, n); return mat(1)(0); } // Main function def main(args : Array[ String ]) = { val in = new Scanner(System.in); val num = in.nextInt(); println(fibb(num)); } } |
-
upload with new input
-
result: Success time: 0.2s memory: 211904 kB returned value: 0
7
13
-
result: Success time: 0.2s memory: 211904 kB returned value: 0
6
8
-
result: Success time: 0.2s memory: 211904 kB returned value: 0
5
5
-
result: Runtime error time: 0.04s memory: 211456 kB signal: -1
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at Main$.main(Main.scala:49) at Main.main(Main.scala)



