classSolution { publicintfib(int n) { if (n < 2) { return n; } intp=0, q = 0, r = 1; for (inti=2; i <= n; ++i) { p = q; q = r; r = p + q; } return r; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intfib(int n){ if (n < 2) { return n; } int p = 0, q = 0, r = 1; for (int i = 2; i <= n; ++i) { p = q; q = r; r = p + q; } return r; } };
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var fib = function(n) { if (n < 2) { return n; } let p = 0, q = 0, r = 1; for (let i = 2; i <= n; i++) { p = q; q = r; r = p + q; } return r; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12
funcfib(n int)int { if n < 2 { return n } p, q, r := 0, 0, 1 for i := 2; i <= n; i++ { p = q q = r r = p + q } return r }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12
intfib(int n) { if (n < 2) { return n; } int p = 0, q = 0, r = 1; for (int i = 2; i <= n; ++i) { p = q; q = r; r = p + q; } return r; }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: deffib(self, n: int) -> int: if n < 2: return n p, q, r = 0, 0, 1 for i inrange(2, n + 1): p, q = q, r r = p + q return r
funcmultiply(a, b matrix) (c matrix) { for i := 0; i < 2; i++ { for j := 0; j < 2; j++ { c[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] } } return }
funcpow(a matrix, n int) matrix { ret := matrix{{1, 0}, {0, 1}} for ; n > 0; n >>= 1 { if n&1 == 1 { ret = multiply(ret, a) } a = multiply(a, a) } return ret }
funcfib(n int)int { if n < 2 { return n } res := pow(matrix{{1, 1}, {1, 0}}, n-1) return res[0][0] }
classSolution: deffib(self, n: int) -> int: if n < 2: return n q = [[1, 1], [1, 0]] res = self.matrix_pow(q, n - 1) return res[0][0] defmatrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]: ret = [[1, 0], [0, 1]] while n > 0: if n & 1: ret = self.matrix_multiply(ret, a) n >>= 1 a = self.matrix_multiply(a, a) return ret
defmatrix_multiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: c = [[0, 0], [0, 0]] for i inrange(2): for j inrange(2): c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] return c