A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
30
Task/Fibonacci-sequence/D/fibonacci-sequence-2.d
Normal file
30
Task/Fibonacci-sequence/D/fibonacci-sequence-2.d
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import std.stdio, std.bigint;
|
||||
|
||||
T fibonacciMatrix(T=BigInt)(size_t n) {
|
||||
int[size_t.sizeof * 8] binDigits;
|
||||
size_t nBinDigits;
|
||||
while (n > 0) {
|
||||
binDigits[nBinDigits] = n % 2;
|
||||
n /= 2;
|
||||
nBinDigits++;
|
||||
}
|
||||
|
||||
T x=1, y, z=1;
|
||||
foreach_reverse (b; binDigits[0 .. nBinDigits]) {
|
||||
if (b) {
|
||||
x = (x + z) * y;
|
||||
y = y ^^ 2 + z ^^ 2;
|
||||
} else {
|
||||
auto x_old = x;
|
||||
x = x ^^ 2 + y ^^ 2;
|
||||
y = (x_old + z) * y;
|
||||
}
|
||||
z = x + y;
|
||||
}
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
void main() {
|
||||
writeln(fibonacciMatrix(1_000_000));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue