Nine chapters algorithm surface question 63 fast power

Source: Internet
Author: User

Nine Chapters count judges Net-original website

http://www.jiuzhang.com/problem/64/


Topics

Computes (a^n)%b, where a, B and N are all 32-bit integers. For example (2^31)%3 = 2.


Online test

http://lintcode.com/zh-cn/problem/fast-power/


Answer

First we need to know a theorem for the MoD operation:

(A * b)% P = (a% p * b% p)% p

By this theorem we can know

Original A^n% B

1. If n is an odd number can be converted to (a^ (N/2) * a^ (N/2) * a)%b = ((a^ (N/2)%b * a^ (N/2)%b)%b * (a)%b)%b

2. If n is an even number can be converted to (a^ (N/2) * a^ (N/2))%b = (a^ (N/2)%b * a^ (N/2)%b)%b

Because know a^1 = A, a^0=1,

And then recursively go for a^n, so that each time we have two minutes n, our actual time complexity is O (log (n)).

So when n is particularly large, then exponentiation becomes particularly fast.


Nine-Chapter algorithm surface question 63 fast power

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.