为什么我没有为第n个Fibo编号的实现获得正确的输出?

时间:2014-09-23 14:38:19

标签: c++ fibonacci

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
void mul ( long long f[2][2], long long m[2][2] );

void power (long long f[2][2], long long int n );
int fibo (long long int n);
int main (void)
{
    int c;
    cin>>c;
    while (c!= 0)
    {
        int n,val;

        cin>>n;
        val = fibo(n);
        cout<<val<<"\n";
        c--;
    }
    return 0;
} 

int fibo (long long int n)
{
    long long f[2][2] = {{1,1},{1,0}};
    if ( n == 0 )
        return 0;
    else
        power(f,n-1);
    return f[0][0];            
}


void power (long long f[2][2], long long int n )
{
    if ( n == 0 )
        return;
    long long m[2][2] = {{1,1},{1,0}};
    if ( n % 2 == 0 )
    {
        mul(f,f);
        power(f,n/2);
    }
    else
    {
        mul(f,f);
        mul(f,m);
        power(f,(n-1)/2);
    }
}

void mul ( long long f[2][2], long long m[2][2] )  
{ 
    long long x = f[0][0]*m[0][0] + f[0][1]*m[1][0];
    long long y = f[0][0]*m[0][1] + f[0][1]*m[1][1];
    long long z = f[1][0]*m[0][0] + f[1][1]*m[1][0];
    long long w = f[1][0]*m[0][1] + f[1][1]*m[1][1];
    f[0][0] = x;
    f[0][1] = y;
    f[1][0] = z;
    f[1][1] = w;
}

我通过平方方法使用矩阵求幂来制作这段代码。但是,我没有得到正确的答案。这是为什么? 为什么我没有为此获得Fibo号码的正确输出?我得到输出

3rd Term: 8
4th Term: 21
5th Term: 55
6th Term: 377

为什么会这样?我尝试使用调试器,但我无法发现错误。

1 个答案:

答案 0 :(得分:1)

power(...)函数看起来很麻烦。怎么样:

void power (long long f[2][2], long long int n )
{
    if ( n == 1 || n == 0 )  // if n == 1, the matrix f^1 should be kept untouched.
        return;              // if n == 0, f should be an identity. it is
                             // a special case here because of your divide-and-
                             // conquer logic.
    long long m[2][2] = {{1,1},{1,0}};
    if ( n % 2 == 0 )
    {
        power(f,n/2);        // given f = m^(n/2) is ready
        mul(f,f);            // m^n = m^(n/2) x m^(n/2)
    }
    else
    {
        power(f,(n-1)/2);    // given f = m^((n-1)/2) is ready
        mul(f,f);            // m^(n-1) = m^((n-1)/2) x m^((n-1)/2)
        mul(f,m);            // m^n = m^(n-1) x m
    }
}