杭电1420 Prepared for New Acmer

来源:互联网 发布:云数据财富平台 编辑:程序博客网 时间:2024/06/03 18:07

 注意java要用long

也就是64位

利用公式a*b%c=((a%c)*b)%c,这样每一步都进行这种处理,这就解决了a^b可能太大存不下的问题,但这个算法的时间复杂度依然没有得到优化

想要了解算法请看(快速幂算法):

http://blog.csdn.net/bruce_suxin/article/details/54957763


import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        while (sc.hasNext()) {            int n = sc.nextInt();            for (int i = 0; i < n; i++) {                long a = sc.nextLong();                long b = sc.nextLong();                long c = sc.nextLong();                System.out.println(f(a, b, c));            }        }    }    public static long f(long a, long b, long n) {        long ret = 1;        while (b-- > 0) {            ret = a * ret % n;        }        return ret;    }}

0 0
原创粉丝点击