题解 | #快速乘#

快速乘

http://www.nowcoder.com/practice/043c66e95fe548d0b8e56c1830330f93

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        long a;
        long b;
        long p;
        while (n-- > 0) {
            a = input.nextLong();
            b = input.nextLong();
            p = input.nextLong();
            if (a > b) {
                System.out.println(cal(a, b, p));
            } else {
                System.out.println(cal(b, a, p));
            }

        }
    }

    public static long cal(long a, long b, long p) {
        long res = 0;
        //a*b=b个a相加 = b/2个(a+a)相加……
        while (b > 0) {
            if (b % 2 == 1) {
                b--;
                res = (res + a) % p;
            }
            b /= 2;
            a = (a + a) % p;
        }
        return res;
    }
}

全部评论

相关推荐

09-21 21:14
门头沟学院
否极泰来来来来:和他说:这里不好骂你,我们加个微信聊
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务