A binary method for solving the Fibonacci sequence numbers of super-large items

Source: Internet
Author: User
Tags int size

We write the series:

fibonacci[0] = 0,fibonacci[1] = 1

Fibonacci[n] = fibonacci[n-1] + fibonacci[n-2] (n >= 2)

it can be written in the form of matrix multiplication:

The right continuous expansion will be:

The following is the calculation of an O (log (n)) algorithm:

The code is as follows:

/* Solve any Fibonacci sequence value, enter an item to be calculated n, output the Fibonacci value corresponding to the item due to the large value, resulting in 1000000007 of the remainder */#include <iostream> #include <cstdio>

using namespace Std;

struct Matrix {__int64 a[2][2];};

Matrix E;
	void inite (int size)//Initialize the unit matrix {for (int i=0;i<size;i++) {for (int j=0;j<size;j++) e.a[i][j]= (I==J);
	}} Matrix Matrixmul (Matrix A,matrix B)//two matrix multiplied by {matrix C;
	int i,j,k;
			for (i=0;i<2;i++) {for (j=0;j<2;j++) {c.a[i][j]=0;
				for (k=0;k<2;k++) {C.a[i][j] + = ((a.a[i][k]%1000000007) * (b.a[k][j]%1000000007));
			c.a[i][j]%=1000000007;
}}} return C;
	} Matrix Matrixpow (Matrix A,__int64 N)//matrix fast binary n power {matrix t=e;
		while (n>0) {if (1&n)//n is an odd T=matrixmul (t,a);
		A=matrixmul (A,a);
	n >>= 1;
} return t;
	} int main (void) {__int64 n;
	Matrix matrix,m;
	Inite (2); while (scanf ("%i64d", &n)!=eof) {if (n==1| |
		n==2) printf ("1\n");     else {matrix.a[0][0]=1;
			Constructs the initial matrix matrix.a[0][1]=1; Matrix.a[1][0]=1;
			matrix.a[1][1]=0;
			M=matrixpow (matrix,n-1);
		printf ("%d\n", (M.a[0][0])%1000000007);
}} return 0; }


Screenshots are as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.