-2

This code is a translation from pseudo-code in a mathemathics wiki to resolve Fibonacci problem in O log(n).

The problem comes when you want to change the seeds of fibonacci (1,0), this is most mathematical question and complexity question than programatically...

So... Where to put A and B to start for example with seeds 5,6?

Thanks for your time!

public static BigInteger Fib(int A, int B, int n)
        {
            if (n <= 0)
                return 0;

            n = n - 1;
            _auxOne = 0;
            _auxTwo = 1;

            Matrix[0, 0] = _auxTwo; //a
            Matrix[0, 1] = _auxOne; //b
            Matrix[1, 0] = _auxOne; //c
            Matrix[1, 1] = _auxTwo + _auxOne; //d

            while (n > 0)
            {
                if (n % 2 != 0)
                {
                    _auxOne = Matrix[1, 1] * Matrix[0, 1] + Matrix[1, 0] * Matrix[0, 0]; //(db+ca)
                    _auxTwo = Matrix[1, 1] * (Matrix[0, 1] + Matrix[0, 0]) + Matrix[1, 0] * Matrix[0, 1]; //(d(b+a)+cb)
                    Matrix[0, 0] = _auxOne;
                    Matrix[0, 1] = _auxTwo;
                }
                _auxOne = BigInteger.Pow(Matrix[1, 0], 2) + BigInteger.Pow(Matrix[1, 1], 2); //(c²+d²)
                _auxTwo = Matrix[1, 1] * (2 * Matrix[1, 0] + Matrix[1, 1]); //(d*(2c+d))
                Matrix[1, 0] = _auxOne;
                Matrix[1, 1] = _auxTwo;

                n = n / 2;
            }
            return Matrix[0, 0] + Matrix[0, 1];
        }
M. Winter
  • 29,928
Ratiess
  • 19

1 Answers1

0

The algorithm (together with its $8$-lines implementation) shown in this answer computes $F_n$ and $F_{n-1}$ in at most $2+2\lceil\log_2 n\rceil$ integer multiplications. The space of sequences $\{s_n\}_{n\geq 0}$ fulfilling $s_{n+2}=s_{n+1}+s_n$ for any $n\geq 0$ is a vector space with dimension $2$ and the sequences $\{F_n\}_{n\geq 0}$ and $\{F_{n-1}\}_{n\geq 0}$ provide a base of such space. It follows that for any seeds $s_0,s_1$ we have $$ s_n = A\cdot F_n + B\cdot F_{n-1} $$ and the constants $A,B$ just depend on $s_0,s_1$. By defining $F_{-1}=1$ we get $$ s_n = s_1 F_n + s_0 F_{n-1} $$ hence the computation of $s_n$ can be performed in at most $4+2\lceil\log_2 n\rceil$ integer multiplications for any set of integer seeds. In the case $s_0=5, s_1=6$ we have $$ s_n = 6F_{n}+5F_{n-1} = F_n + 5 F_{n+1}.$$

Jack D'Aurizio
  • 353,855