c++ 暴力版
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
int fib(int n){
if (n < 2)
return n;
int fib1 = 1, fib2 = 1, fib3 = 1;
for (int i = 2; i < n; i++){
fib3 = (fib2 + fib1) % 10000;
fib1 = fib2;
fib2 = fib3;
}
return fib3;
}
int main(){
long long s = clock();
printf("%d\n", fib(1000000000) );
long long e = clock();
printf("%d\n", e - s);
return 0;
}
使用c++ 暴力求解,事件复杂度O(n),在i5上运行10秒左右,开优化后缩短一半
Python 快速幂,简单粗暴。。。
import numpy as np
M = 10000
def power(m, n):
if n <= 1:
return m
t = power(m, n // 2)
if n % 2 == 0:
return np.mod(np.dot(t, t), M)
return np.mod(np.dot(m, np.dot(t, t)), M)
def fib(n):
if n < 2:
return n
mat = np.array([[1, 1], [1, 0]])
t = power(mat, n)[0][1]
return t
print(fib(1000000000))
# 6875