我正在尝试编写一个程序,以查找大整数'n'的2的幂。
我收到无法将double转换为BigInteger的错误。所以我想知道可以将double / long转换为BigInteger吗?
import java.math.*;
import java.util.Scanner;
public class LargePow2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("n = ?");
int n = sc.nextInt();
System.out.println("2^" + n + " is \n" + pow2(n));
}
public static BigInteger pow2(long n){
BigInteger result = BigInteger.ONE;
result = Math.pow(n, 2);
return result;
}
}
您可以将double转换为BigDecimal,然后转换为BigInteger:
BigInteger result = BigDecimal.valueOf(Math.pow(n, 2)).toBigInteger();