Fibonacci optimization: Rapid power + Matrix Multiplication

Source: Internet
Author: User

 

Question: Can you obtain the nth Fibonacci number? 0 <n <maxlongint

The output result mod32768 is too large.

 

 

 

Idea: Generally, the methods for finding the Fibonacci series are recursive, dynamic, or rolling optimization, but the space or time complexity is too high, now there is an optimization algorithm that uses a matrix plus a rapid power to maintain the time complexity in logn.

Initialize a 2 × 2 matrix. If the initial value is {,}, it indicates {A2, A1, A1, a0}. After the square of this matrix is obtained, {2, 1, 1, 0} represents {A3, A2, A2, A1} respectively, so that the law can be obtained. In fact, this algorithm is mainly optimized on the fast power. As for the matrix, the storage format is different.

 

Code:

# Include <iostream> using namespace STD; // matrix struct MTA {int A [2] [2] ;}; // multiply the matrix, A * B mta mul (mta a, mta B) {mta c; For (INT I = 0; I <2; I ++) {for (Int J = 0; j <2; j ++) {C. A [I] [J] = 0; For (int K = 0; k <2; k ++) {C. A [I] [J] + = (. A [I] [k] * B. A [k] [J]) % 32768 ;}} return C ;}int main () {int N; MTA res; MTA base; // calculate the nth Fibonacci number while (CIN> N) {res. A [0] [0] = 1; Res. A [0] [1] = 0; Res. A [1] [0] = 0; Res. A [1] [1] = 1; base. A [0] [0] = 1; base. A [0] [1] = 1; base. A [1] [0] = 1; base. A [1] [1] = 0; // matrix fast power while (n! = 0) {If (N & 1) {res = MUL (Res, base) ;}base = MUL (base, base); N/= 2 ;} cout <res. A [0] [1] <Endl;} return 0 ;}

 

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.