Matrix Quick power Template

Source: Internet
Author: User

# Define Matr 105 // matrix size struct mat // matrix structure, a indicates the content, size matrix starts from 1 {int a [Matr] [Matr], size; mat () {size = 0; memset (a, 0, sizeof (a) ;}}; void print (mat m) // output matrix information. For debug, use {int I, j; printf ("% d \ n", m. size); for (I = 0; I <m. size; I ++) {for (j = 0; j <m. size; j ++) printf ("% d", m. a [I] [j]); printf ("\ n") ;}} mat multi (mat m1, mat m2, int mod) // multiplication of two equal matrices, for a sparse matrix, there are 0 optimizations that do not require computation {mat ans = mat (); ans. size = m1.size; for (int I = 1; I <= m1.size; I ++) for (int j = 1; j <= m2.size; j ++) if (m1.a [I] [j]) // sparse matrix Optimization for (int k = 1; k <= m1.size; k ++) ans. a [I] [k] = (ans. a [I] [k] + m1.a [I] [j] * m2.a [j] [k]) % mod; return ans;} mat quickmulti (mat m, int n, int mod) // binary fast power {mat ans = mat (); int I; for (I = 1; I <= m. size; I ++) ans. a [I] [I] = 1; ans. size = m. size; while (n) {if (n & 1) ans = multi (m, ans, mod); m = multi (m, m, mod ); n> = 1;} return ans;}/* ans ^ = n-> mat ans = mat (); ans. size = Size; initialize the ans matrix ans = quickmulti (ans, n, mod );*/

 

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.