Rapid Algorithm for poj 3070 Fibonacci Matrix

Source: Internet
Author: User

It is the matrix algorithm of Fibonacci, but the addition is because the number is large, so we need to take the 10000 modulo, And the modulo can be used to calculate the matrix.

The data in this question is not strong, but the value is limited to an integer, so it can be 0 Ms seconds.

The following program is very clear, because several small functions are separated, which is suitable for beginners.

# Include <stdio. h> const int mod = 10000; void mulonematrix (INT f [2] [2]) {int A = f [0] [0]; int B = f [1] [0]; F [0] [0] = (a + B) % MOD; F [0] [1] =; f [1] [0] = A; F [1] [1] = B;} inline void mulmat (INT LF [2] [2], int RF [2] [2]) {int A = LF [0] [0] * Rf [0] [0] + LF [0] [1] * Rf [1] [0]; int B = LF [0] [0] * Rf [0] [1] + LF [0] [1] * Rf [1] [1]; int c = LF [1] [0] * Rf [0] [0] + LF [1] [1] * Rf [1] [0]; int d = LF [1] [0] * Rf [0] [1] + LF [1] [1] * Rf [ 1] [1]; LF [0] [0] = A % MOD; LF [0] [1] = B % MOD; LF [1] [0] = C % MOD; LF [1] [1] = D % MOD;} void powmatrix (INT f [2] [2], int N) {If (n <= 1) return; powmatrix (F, N> 1); mulmat (F, F); If (N & 1) mulonematrix (f );} int calfibonacci (int n) {int f [2] [2] = {1, 1}, {1, 0}; // FN + 1, FN, FN, fn-1powMatrix (F, n-1); Return f [0] [0];} int main () {int N; while (scanf ("% d", & N) &-1! = N) {If (n = 0) puts ("0"); else printf ("% d \ n", calfibonacci (n);} 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.