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;
    }
  • 相关阅读:
    cmd常用指令
    python笔记01-05
    python安装过程中的一些问题
    初始化spring容器的一种方式
    切入点范式
    spring的list注入多个值
    Statement和PreparedStatement有什么区别?哪个效率高?
    sql 的四种隔离级别
    简单的spring核心配置文件编写
    spring
  • 原文地址:https://www.cnblogs.com/td15980891505/p/5402832.html
Copyright © 2011-2022 走看看