HDU OJ 1061 rightmost Digit (Fast power algorithm)

Source: Internet
Author: User
Tags modulus

The first step here is to explain the fast power algorithm:

Fast power-take modulus algorithm

On the website has not found a detailed description and explanation of the fast power algorithm, here, I give a full explanation of the fast power algorithm, with the C language, readers of different languages have to change bits, after all, read C more people ~

The so-called fast power, in fact, is the abbreviation of fast Power modulus, simply speaking, is to quickly find a power mode ( residual ). In the process of programming, it is often necessary to find some large numbers for the remainder of a number, in order to get a faster, more computational scope of the algorithm, resulting in a fast power-taking modulus algorithm. [ Some readers are reflected in the fast power of the part of the vague, so the article was modified here, made a more detailed supplement, to make more readers at a glance]

Let's start with a simple example: ask for a^b% c =?

Algorithm 1. first, the algorithm is designed directly:

int ans = 1;

for (int i = 1;i<=b;i++)

{

Ans = ans * A;

}

Ans = ans% c;

The time complexity of this algorithm is reflected in the for Loop, which is O(b). There is an obvious problem with this algorithm, if a and the b too big, it can easily overflow.

So, let's take a look at the first improvement: Before you talk about this scenario, there is a formula: a^b%c= (a%c) ^b%c. This formula should be learned in discrete mathematics or number theory, but here to facilitate the reading, or to give proof:

Lemma 1: a^b%c = (a%c) ^b%c

The above formula is the lemma of the formula below, that is, the remainder of the product is equal to the remainder of the product.

After proving the above formula, we can first let a about C to take the remainder, this can greatly reduce The size of a,

So there is no need to think about the improvement:

Algorithm 2:

int ans = 1;

A = a% c; Add this sentence

for (int i = 1;i<=b;i++)

{

Ans = ans * A;

}

Ans = ans% c;

Smart readers should be able to think of, since a factor after the remainder of the multiplication and then take the rest of the remaining constant, then the new ans can also take redundancy, so get a better version of the improved.

Algorithm 3:

int ans = 1;

A = a% c; Add this sentence

for (int i = 1;i<=b;i++)

{

Ans = (ans * A)% c;// here to take more than one more time

}

Ans = ans% c;

This algorithm has no improvement in time complexity, still O (b), but it is much better, but in the case of C too large, it is still possible to time out, so we have introduced the following fast power algorithm.

The fast power algorithm relies on the following obvious formulas, which I will not prove.

Then we can get the following algorithm:

Algorithm 4:

int ans = 1;

A = a% c;

if (b%2==1)

Ans = (ans * a) mod C; if it's odd, take one more step, and you can calculate the ans in advance.

K = (a*a)% C; let's take a2 instead of a .

for (int i = 1;i<=b/2;i++)

{

Ans = (ans * k)% c;

}

Ans = ans% c;

We can see that we turn the complexity of time into O (B/2). Of course, this kind of symptom does not cure. But we can see that when we make k = (A * a) mod C , the state has changed and the final result we require is (k)B/2 mod C instead of the original a< /c5>b mod c, so we find that this process can be iterative. Of course, for odd cases there will be a more a mod c, so in order to complete the iteration, when b is odd, we pass

Ans = (ans * a)% C; to make up for the extra item, the rest of the section can be iterated.

When the b=0 is down, all the factors are multiplied and the algorithm ends. You can then complete the time in O(log b) . So, with the final algorithm: the Fast Power algorithm.

Algorithm 5: fast Power algorithm

int ans = 1;

A = a% c;

while (b>0)

{

if (b% 2 = = 1)

Ans = (ans * a)% C;

b = B/2;

A = (A * a)% C;

}

Structure the above code, which is written as a function:

int powermod (int a, int b, int c)

{

int ans = 1;

A = a% c;

while (b>0)

{

if (b% 2 = = 1)

Ans = (ans * a)% C;

b = B/2;

A = (A * a)% C;

}

return ans;

}

The time complexity of this algorithm is O(logb), which can be passed in almost all program Design (contest) process, and is one of the most commonly used algorithms at present.

The following information is for reference only:

Extension: There is a derivation of the algorithm for fast power, which can also be thought from another angle.

=? To solve this problem, we can also consider from the conversion of the binary:

Convert the ten -binary b into an 2 -binary expression:

Note here that either the0, or for1, if an item, then this one is1, which corresponds to the above algorithm in the processbis an even number of cases, for1corresponds to thebis an odd number of cases[do not reverse, the reader's own analysis, you can contactTenin-process turn2the method of the binary], we fromMultiply it in turn. For each item's calculation, the result of the last item is calculated using the square of the result of the previous item. For the result of the request, the lastansYou don't have to multiply it .[because this value is1], for1The item is multiplied by this item to take the remainder. This algorithm and the above algorithm in essence is the same, the reader can self-analysis, here I said not much to say, I hope this article will help readers grasp the fast power algorithm of the knowledge point, of course, to real mastery, not much practice is not possible.

(By night せ︱ deep thanks to the author) the reference is a very good explanation on the Internet.


With the basis of the previous, and then we have to do the problem is more convenient:

Rightmost DigitTime limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 35199 Accepted Submission (s): 13362


Problem Descriptiongiven A positive integer N, you should output the most right digit of n^n.

Inputthe input contains several test cases. The first line of the input was a single integer T which is the number of test cases. T test Cases follow.
Each test case is contains a single positive integer N (1<=n<=1,000,000,000).

Outputfor Each test case, you should output the rightmost digit of n^n.

Sample Input
234

Sample Output
HintIn the first case, 3 * 3 * 3 = rightmost, so the digit is 7.In the second case, 4 * 4 * 4 * 4 = The rightmost digit is 6.

AUTHORIGNATIUS.L the meaning of the topic has been very clear, that is, to find the single digit of n^n, it is equivalent to the single digit of the MoD 10 operation, here directly with the fast power algorithm, you can get results, the topic given n may be relatively large, so a long long is more insurance.
Here is the AC code:
#include <iostream> #include <cstdio>using namespace Std;long long  calculation (long long A,long long B, int c)//fast power algorithm {    int ans=1;    a=a%c;    while (b>0)    {        if (b%2==1)            ans= (ans*a)%c;        B=B/2;        A= (a*a)%c;    }    return ans;} int main () {    int t;    Long long n,sum;    scanf ("%d", &t);    while (t--)    {       scanf ("%lld", &n);       Sum=calculation (n,n,10);       printf ("%d\n", sum);    }    return 0;}



HDU OJ 1061 rightmost Digit (Fast power algorithm)

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.