简体   繁体   中英

Double/ Long to BigInteger

I'm trying to make a program that finds 2 to the power of the large integer 'n'.

I get the error that double cannot be converted to BigInteger. So I was wondering can double/long be converted to 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.

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

you can convert the double to BigDecimal and then into a BigInteger:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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