java中multiply⽤法_JavaBigIntegermultiply()⽤法及代码⽰
例
java.math.BigInteger.multiply(BigInteger val)⽤于计算两个BigInteger的乘法。由于BigInteger类内部使⽤整数数组进⾏处理,因此对BigInteger对象的操作不如对基元进⾏的操作快。
⽤法:
public BigInteger multiply(BigInteger val)
参数:此⽅法接受参数val,该参数是要与该BigInteger相乘的值。
返回值:此⽅法返回⼀个保存乘法(此* val)的BigInteger。
下⾯的程序⽤于说明BigInteger的multiply()⽅法。
⽰例1:
// Java program to demonstrate
// multiply() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// BigInteger object to store result
BigInteger mult;
// For user input
// Use Scanner or BufferedReader
// Two objects of String created
// Holds the values to calculate the multiplication
String input1 = "012345678901234567"
+ "654632498739473";
String input2 = "0123456789012345"
+ "61247612748612746";
// Convert the string input to BigInteger
BigInteger a
= new BigInteger(input1);
BigInteger b
= new BigInteger(input2);
// Using multiply() method
mult = a.multiply(b);
// Display the result in BigInteger
System.out.println("The multiplication of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + mult);
}
}
输出:
The multiplication of
12345678901234567654632498739473
and
12345678901234561247612748612746
is
152415787532388282591353462245536419067346861445890674421122858⽰例2:
// Java program to demonstrate
// multiply() method of BigInteger
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
// BigInteger object to store result
BigInteger mult;
// For user input
// Use Scanner or BufferedReader
/
/ Two objects of String created
// Holds the values to calculate the multiplication
String input1 = "012345678901234567"
+ "8901234567890123"
+ "4567890123456789"
+ "0123456789012345"
+ "6789012345678901"
+ "654632498739473";
String input2 = "0123456789012345"
+ "6789012345678901"
+ "2345678901234567"
+ "8901234567890123"
+ "4567890123456789"
+ "61247612748612746";
// Convert the string input to BigInteger
BigInteger a
= new BigInteger(input1);
BigInteger b
= new BigInteger(input2);
// Using multiply() method
mult = a.multiply(b);
// Display the result in BigInteger
System.out.println("The multiplication of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + mult + "\n");
// Using double to hold the result
double d = Double.String());
// Display the result in double
System.out.println("Using double, multiplication is "
+ d);
}
}
输出:
object to
The multiplication of 1234567890123456789012345678901234567890123456789012345678901234567890123456789016546324987
and
1234567890123456789012345678901234567890123456789012345678901234567890123456789612476127486
is
1524157875323883675049535156256668194500838287337600975522511812231126352691000898503653250
Using double, multiplication is 1.5241578753238838E190
从上⾯的⽰例中可以明显看出,使⽤BigInteger时数据是完全精确的。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论