POJ 1995 Fast Power modulo

Source: Internet
Author: User

Recently done a template problem, the difficulty is general, you can learn a quick power, attached to the rules of the modulo operation,

/* Modulo arithmetic rules
(A + b)% P = (a% p + b% p)% p (1)
(A-B)% P = (a% p-b% p)% p (2)
(A * b)% P = (a% p * b% p)% p (3)
A ^ b% P = ((a% p) ^b)% P (4)

#include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> using namespace
Std
    int pow_mod (int a,int b,int m) {if (b = = 0) return 1;
    int x = Pow_mod (a,b/2,m);
        Long Long ans = (long long) x * x m;//(A1 ^b1 + a2^b2) mod (n) = (A1 ^b1mod (n) + a2^b2mod (n)) mod (n) if (b 2 = = 1)
        Ans = ans * a% m;  /* modulo operation rule (a + b)% P = (a% p + b% p)% p (1) (A-a)% P = (a% p-b p)% P (2) (A * b)% P = (a% p * b
% p)% p (3) a ^ b% P = ((a% p) ^b)% P (4) */return (int) ans;
    } int main () {int num;
    Long Long T, M, N, a, B;
    a long long sum;
    scanf ("%d", &num);
        for (int i = 0;i < num;i++) {sum = 0;
        scanf ("%lld", &m);
        scanf ("%lld", &n);
            for (int j = 0;j < n;j++) {scanf ("%lld%lld", &a,&b);
        Sum + = Pow_mod (a,b,m);
    } printf ("%lld\n", sum%m);
} return 0; }


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.