Ultraviolet A 10229-modular Fibonacci

Source: Internet
Author: User

Question: Calculate the N fib number and the 2 ^ m model.

Analysis: divide, fast power.

For more information, seeFibonacci SeriesHttp://blog.csdn.net/mobius_strip/article/details/8222309)

Medium4. Calculation of Fib 3: Divide and conquer;

Set JN to the number of rabbits with fertility in the nth month, and an to the number of rabbits in the first month. The following recursive matrix is obtained:

Where

This can be simply proved by mathematical induction, and we will not prove it here;

Then, we apply the preceding Rapid power algorithm to the matrix and obtain a logarithm-level fib algorithm.

Note: When n is 0.

# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD;/*, the result is in ANS */long mat [2] [2] = {0, 1, 1}; long ans [2] [2]; long long tem [2] [2]; // matrix multiplication void MUL (long a [] [2], long B [] [2], long long C [] [2], int mod) {for (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) A [I] [J] = 0ll; For (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) for (int K = 0; k <2; ++ K) A [I] [J] = (a [I] [J] + B [I] [k] * C [k] [J]) % MOD ;} // matrix copy void copy (long a [] [2], long B [] [2]) {for (INT I = 0; I <2; ++ I) for (Int J = 0; j <2; ++ J) A [I] [J] = B [I] [J];} // matrix fast power void spow (long N, int mod) {If (n = 1ll) Copy (ANS, mat); else {spow (N/2ll, moD); copy (TEM, ANS); MUL (ANS, TEM, TEM, MoD); If (N % 2ll) {copy (TEM, ANS); MUL (ANS, TEM, mat, MoD) ;}}int main () {int n, m; while (CIN >>n> m) {If (n> 1) {spow (n, 1 <m); cout <ans [0] [1] <Endl;} else cout <0 <Endl;} return 0 ;}

Ultraviolet A 10229-modular Fibonacci

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.