位运算之64位整数乘法

题目链接:

参考链接:https://blog.csdn.net/yo_bc/article/details/70339543

常用定理:(a*b)%c = ((a%c)*(b%c)) % c

     (m1+m2+m3+m4)%c = ((m1%c) + (m2%c)+ (m3%c)+ (m4%c)) % c

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        long a=sc.nextLong();
        long b=sc.nextLong();
        long p=sc.nextLong();
        System.out.println(fun(a,b,p));

    }

    private static long fun(long a, long b, long p) {
        if (a>b) {
            long[] swap = swap(a,b); 
            a = swap[0]; 
            b = swap[1];
        }
        long res=0;
        while(b!=0){
            if ((b&1)!=0) {
                res=(res+a)%p;
            }
            a=a*2%p;//这里使用了定理2
            b=b>>1;
        }
        return res;
    }
    private static long[] swap(long a, long b){ 
        long temp = a;
        a = b; 
        b = temp; 
        return new long[]{a,b};
    }


}

猜你喜欢

转载自www.cnblogs.com/clarencezzh/p/10323669.html