1600: Big Mod (Modulo of large numbers)

Source: Internet
Author: User
Result Time Limit Memory limit Run times AC times Judge
3 S 8192 K 1756 336 Standard

Calculate

 

 

For large valuesB,P, AndMUsing an efficient algorithm. (That's right, this problem has a time dependency !!!.)

Input

Three integer values (in the orderB,P,M) Will be read one number per line.BAndPAre integers in the range 0 to 2147483647 random Sive.MIs an integer in the range 1 to 46340 random Sive.

Output

The result of the computation. A single integer.

Sample Input

 

3181321717176532374859302938236123

Sample output

 

13213195/*
*/
  1. # Include <stdio. h>
  2. # Include <memory>
  3. Int main ()
  4. {
  5. Int A, B, N;
  6. While (scanf ("% d", & A, & B, & N )! = EOF)
  7. {
  8. Bool B2 [35];
  9. Memset (B2, 0, sizeof (B2 ));
  10. Int TMP = B, I, D = 1;
  11. For (I = 0; TMP> 0; I ++)
  12. {
  13. B2 [I] = TMP % 2;
  14. TMP = tmp/2;
  15. }
  16. For (; I> = 0; I --)
  17. {
  18. D = D * D % N;
  19. Int AA = A % N;
  20. If (B2 [I] = 1)
  21. D = D * Aa % N;
  22. }
  23. Printf ("% d/N", d );
  24. }
  25. Return 0;
  26. }

Method 2: ultra-short code

# Include <cstdio>
Int B, P, M, K;
Int main ()
{
While (scanf ("% d", & B, & P, & M )! = EOF)
{
For (k = 1, B = B % m; P/= 2, B = B * B % m)
If (P % 2) K = K * B % m;
Printf ("% d \ n", K % m );
}
Return 0;
}

 

Method 3: lower recursion time

# Include <cstdio>
Int m;
Int bigmod (int A, int B)
{
If (! B) return 1;
Int d = bigmod (a, B> 1) % m;
Return B & 1? (D * D % M * A) % m :( D * D) % m;
}
Int main ()
{
Int A, B;
While (scanf ("% d", & A, & B, & M )! = EOF)
{
Int ans = bigmod (a % m, B) % m;
Printf ("% d \ n", ANS );
}
Return 0;
}

The shortest code for rapid modulo operation (k = 1, A = A % m; B; B >>= 1, A = A * A % m) if (B & 1) k = K * A % m; find a ^ B (mod m) K % m as the answer.

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.