The last three digits of the n-th-square of M

Source: Internet
Author: User

The n-th of positive integer m may be a very large number, and we only ask for the last three digits of that number

Example 1:

For example, input 5 and 3, 5 3 is 125, the output is 125

Example 2:

For example, the input 2 and 10 2 10 is 1024, the output is 24

Example 3:

For example, the input 111 and 5 111 5 is 116850581551, the output is 551

Method One:

Because M is a relatively large number, and the n-th is likely to go out of scope, we can multiply the tree by multiplying the number as a string, multiplying by the phase. But this method is more cumbersome. Because we only take the last three bits, we multiply it by modulo 1000, leaving only the last three digits.

int last_three_number (unsigned int m,unsigned int n) {if (0==n) return 1; if (0==m) return 0; unsigned int i=0,result=1; fo R (; i<n;i++) {   result*=m;   if (1000<=result)   {   result%=1000;   }} return result;
Method Two:

On the basis of method one, multiplication is no longer m*m. Instead, the N/2 power of M times the power of the N/2 of M.

The code is as follows:

int last_three_number1 (unsigned int m,unsigned int n) {if (0==n) return 1; if (0==m) return 0; unsigned int i=0,result=1; w Hile (n!=0) {if (n%2==1) result= (result*m)%1000; m= (m*m)%1000; n/=2;} return result; }





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The last three digits of the n-th-square of M

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.