斐波那契数列

来源:互联网 发布:淘宝助理5天猫用不了 编辑:程序博客网 时间:2024/05/19 15:43

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

int Fibonacci(int n) {    if(n <= 0) return 0;//这里要注意判断小于0的情况    if(n == 1 || n == 2) return 1;    int b = n-2;    int d[2][2];    d[0][0] = 1;    d[0][1] = 0;    d[1][0] = 0;    d[1][1] = 1;    int temp[2][2];    temp[0][0] = 1;    temp[0][1] = 1;    temp[1][0] = 1;    temp[1][1] = 0;    int total[2][2];    total[0][0] = 1;    total[0][1] = 1;    total[1][0] = 0;    total[1][1] = 0;    int to[2][2];    while (b) {        if(b&1){            for(int i = 0; i < 2; i++){                to[i][0] = d[i][0];                to[i][1] = d[i][1];                d[i][0] = d[i][1] = 0;            }            for(int i = 0; i < 2; i++){                for(int j = 0; j< 2;j++)                for(int k = 0; k < 2; k++){                    d[i][j] += to[i][k]*temp[k][j];                }            }        }        for(int i = 0; i < 2; i++){            to[i][0] = temp[i][0];            to[i][1] = temp[i][1];            temp[i][0] = temp[i][1] = 0;        }        for(int i = 0; i < 2; i++){            for(int j = 0; j< 2;j++)                for(int k = 0; k < 2; k++){                    temp[i][j] += to[i][k]*to[k][j];                }        }        b>>=1;}return total[0][0]*d[0][0]+total[0][1]*d[1][0];

}

0 0