0
我正在使用下面的代碼解決問題,但我在下面的行中得到一個NullPointerException pw.println(fastMod(a,b,BigInteger.TEN ));功能找到a^b的餘數,其中a,b是正整數
我在返回BigInteger值時收到NullPointerException。 請建議並幫助我。謝謝。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class ModularExponential {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
private static BigInteger fastMod(BigInteger base, BigInteger exponent,BigInteger modulo) {
BigInteger result = BigInteger.ONE;
while (BigInteger.ZERO.compareTo(exponent) > 0) {
if (exponent.testBit(0))
result = (result.multiply(base)).mod(modulo);
exponent = exponent.shiftRight(1);
base = (base.multiply(base)).mod(modulo);
}
return result.mod(modulo);
}
public static String next() throws IOException{
while(! st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public static void main(String[] args) throws IOException{
st = new StringTokenizer("");
BigInteger a,b;
br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while(T-- > 0) {
a = new BigInteger(next());
b = new BigInteger(next());
pw.println(fastMod(a,b,BigInteger.TEN));
}
}
}
類似於'pw = new PrintWriter(....);'缺少。將'pw'改成'System.out'進行測試。 – munyul 2014-09-12 12:41:02
順便說一下,我認爲內置的modPow函數和fastMod函數一樣。 – 2014-09-12 13:46:23