zoukankan      html  css  js  c++  java
  • 快速乘法,幂计算 hdu5666

    在实际应用中为了防止数据爆出,在计算a*b%m和x^n%m时,可以采用此方法。在数论中有以下结论:

            a*b%m=((a%m)*(b*m))%m ;

            (a+b)%m=(a%m+b%m)%m ;

    _int64 Plus(_int64 a, _int64 b,_int64 m) { //计算a*b%m
        _int64 res = 0;
        while (b > 0) {
            if (b & 1)
                res=(res+a)%m;     
            a = (a << 1) % m;    
            b >>= 1;
        }
        return res;
    }
    _int64 Power(_int64 x, _int64 n,_int64 m) { //计算x^n%m
        _int64 res=1;              
        while (n > 0) {              
            if (n & 1)              
                res=(res*x)%m;
            x = (x*x)%m;
            n>>= 1;                 
        }
        return res;
    }

     例题:HDU 5666

    Segment

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
    Total Submission(s): 748    Accepted Submission(s): 290


    Problem Description
        Silen August does not like to talk with others.She like to find some interesting problems.

        Today she finds an interesting problem.She finds a segment x+y=q.The segment intersect the axis and produce a delta.She links some line between (0,0)and the node on the segment whose coordinate are integers.

        Please calculate how many nodes are in the delta and not on the segments,output answer mod P.
     
    Input
        First line has a number,T,means testcase number.

        Then,each line has two integers q,P.

        q is a prime number,and 2q1018,1P1018,1T10.
     
    Output
        Output 1 number to each testcase,answer mod P.
     
    Sample Input
    1 2 107
     
    Sample Output
    0
     
    分析可知。在横坐标为 i 处的直线为 y=(p-i)/i *x,显然gcd(p,i)==1,从而直线上的点只有(0,0)和(i,p-i)为整点。发现了这一点最后不难求出来总的点个数为:
    (p-2)+(p-3)+...+1=(p-1)(p-2)/2 。考虑到中间结果溢出的情况,从而可以采用快速乘法模运算。
    #include<iostream>
    using namespace std;
    _int64 Plus(_int64 a, _int64 b, _int64 m);
    int main() {
        _int64 p,q,T;
        cin >> T;
        while (T--) {
            cin >> q >> p;
            cout << Plus((q-1)%2, q-2, p) << endl;
        }
        return 0;
    }
    _int64 Plus(_int64 a, _int64 b,_int64 m) {
        _int64 res = 0;
        while (b > 0) {
            if (b & 1)
                res = (res + a) % m;
            a = (a+a) % m;    
            b >>= 1;
        }
        return res;
    }
  • 相关阅读:
    mysql-5.7 show engine innodb status 详解
    mysql-5.7 saving and restore buffer pool state 详解
    mysql-5.7 监控innodb buffer pool load 的进度 详解
    python3 functools partial 用于函数的包装器详解
    mysql-5.7 innodb change buffer 详解
    mysqlbackup 重建带有gtid特性的slave
    将python图片转为二进制文本的实例
    nginx: [error] invalid PID number "" in "/run/nginx.pid"
    ubuntu中执行定时任务crontab
    Matplotlib:mpl_toolkits.mplot3d工具包
  • 原文地址:https://www.cnblogs.com/td15980891505/p/5402832.html
Copyright © 2011-2022 走看看