java biginteger sqrt_Java BigInteger sqrt()用法及代码示例

java.math.BigInteger.byteValueExact()是Java SE 9和JDK 9中添加的一个内置函数,该函数返回应用了sqrt()方法的BigInteger平方根的BigInteger值。它与floor(sqrt(n))相同,其中n是一个数字。如果不能将实平方根表示为整数值,则此平方根小于实平方根。

用法:

public BigInteger sqrt()

参数:该方法不带任何参数。

返回值:方法返回此BigInteger的整数平方根。

异常:如果BigInteger为负,则该方法将引发ArithmeticException。

例:

Input: 234876543456

Output: 484640

Explanation: 122 is given as input which is the bigInteger.

The square root of 122 is 11.04536

whose BigInteger equivalent is 11 and using sqrt()

method of BigInteger class we can get

Square root of any BigInteger.

Input: 122

Output: 11

以下示例程序旨在说明BigInteger类的sqrt()方法:

示例1:显示了sqrt()方法在获得31739平方根中的应用。

// Please run this program in JDK 9 or JDK 10

// Java program to demonstrate sqrt() method

import java.math.*;

public class GFG {

public static void main(String[] args)

{

// Creating a BigInteger object

BigInteger big, squareRoot;

big = new BigInteger("31739");

// calculate square root o bigInteger

// using sqrt() method

squareRoot = big.sqrt();

// print result

System.out.println("Square root value of BigInteger " + big

+ " is " + squareRoot);

}

}

输出:

Square root value of BigInteger 31739 is 178

示例2:显示由sqrt()方法引发的异常。

//Please run this program in JDK 9 or JDK 10

// Java program to demonstrate sqrt() method

//and exception thrown by it

import java.math.*;

public class GFG {

public static void main(String[] args)

{

// Creating a BigInteger object

BigInteger big,squareRoot=null;

big = new BigInteger("-2345");

//calculate square root o bigInteger

//using sqrt() method

try {

squareRoot = big.sqrt();

} catch (Exception e) {

e.printStackTrace();

}

// print result

System.out.println("Square root value of BigInteger " + big

+" is "+squareRoot);

}

}

输出:

java.lang.ArithmeticException: Negative BigInteger

at java.base/java.math.BigInteger.sqrt(Unknown Source)

at GFG.main(GFG.java:19)

Square root value of BigInteger -2345 is null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值