题解 | #快速乘#

快速乘

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer st = new StreamTokenizer(br);
        st.nextToken();int q = (int)st.nval;
        for(int i =0;i<q;i++){
            st.nextToken();long a = (long)st.nval;
            st.nextToken();long b = (long)st.nval;
            st.nextToken();long p = (long)st.nval;
            if(a>b){
                System.out.println(cal(a,b,p));
            }else{
                System.out.println(cal(b,a,p));
            }
        } 
    }

    private static long cal(long a, long b, long p) {
        // TODO
        if(b==0) return 0;
        long temp = cal(a,b/2,p)%p;
        return ((temp+temp)%p+((b%2==1)?(a%p):0))%p;
    }
}

全部评论

相关推荐

09-29 11:19
门头沟学院 Java
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务