大整数 快速幂

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3549

最核心的是由于m^n 太大, 存不下了,存下来的复杂度也太高,就只能边运算边取模,看别人的代码才想到。0s 不会很多,就暴力枚举。

import java.math.*;
import java.util.*;

public class Main {
    static BigInteger Fast_Power(BigInteger x ,BigInteger n, BigInteger mod)
    {
        BigInteger ret = BigInteger.ONE;
        while(n.compareTo(BigInteger.ZERO) > 0)
        {
            if(n.mod( BigInteger.valueOf(2) ).compareTo(BigInteger.ONE) == 0)
                ret = ret.multiply(x).mod(mod);
            x = x.multiply(x).mod(mod);
            n = n.divide(BigInteger.valueOf(2));
        }
        return ret;
    }
    static boolean Judge(int m,int n,int k)
    {
        BigInteger mod = BigInteger.ONE, ans = BigInteger.ZERO;
        int i;
        for(i=1; i<=k; i++)
            mod = mod.multiply(BigInteger.valueOf(10));
        for(i=1; i<=m; i++)
        {
            BigInteger a = BigInteger.valueOf(i);
            BigInteger b = BigInteger.valueOf(n);
            ans = ans.add(Fast_Power(a,b,mod)).mod(mod);
        }
        if(ans.mod(mod).compareTo(BigInteger.ZERO) == 0) return true;
        return false;
    }
    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
        int i, m,n;
        while(cin.hasNext())
        {
            m = cin.nextInt();
            n = cin.nextInt();
            for(i=1;; i++)
            {    
                if(Judge(m,n,i)) continue;
                else              break;
            }
            System.out.println(i-1);
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/acmdeweilai/p/3426392.html