简体   繁体   English

Double/ Long 到 BigInteger

[英]Double/ Long to BigInteger

I'm trying to make a program that finds 2 to the power of the large integer 'n'.我正在尝试制作一个程序,找到 2 的大 integer 'n' 的幂。

I get the error that double cannot be converted to BigInteger.我收到 double 无法转换为 BigInteger 的错误。 So I was wondering can double/long be converted to 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;
    }
}

Maybe it is better to avoid the Math.pow() function because it returns the result as double, which is less accurate in case of very large numbers.也许最好避免使用 Math.pow() function,因为它以双精度返回结果,这在非常大的数字的情况下不太准确。

    public static BigInteger pow2(long n){
        return BigInteger.valueOf(n).pow(2);
    }

you can convert the double to BigDecimal and then into a BigInteger:您可以将双精度转换为 BigDecimal,然后再转换为 BigInteger:

BigInteger result = BigDecimal.valueOf(Math.pow(n, 2)).toBigInteger();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM