珀尔 | Math::BigInt->length() 方法
Perl 中的Math::BigInt
模块提供了表示具有任意精度和重载算术运算运算符的整数的对象。
Math::BigInt
模块的length()
方法用于获取给定数字的长度,即给定数字中的位数。
Syntax: Math::BigInt->length()
Parameter: None
Returns: an integer value which represents the length of the given number.
示例 1:使用Math::BigInt->length()
方法计算数字中的位数
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
# Specify number
$num = 78215936043546;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
print "Length of $num is $len.\n";
# Specify another number
$num = 7821593604584625197;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
print "Length of $num is $len.\n";
输出:
Length of 78215936043546 is 14.
Length of 7821593604584625197 is 19.
示例 2:使用Math::BigInt->length()
方法将给定数字分成两半。
#!/usr/bin/perl
# Import Math::BigInt module
use Math::BigInt;
# Specify number
$num = 78215936043546;
# Create BigInt object
$x = Math::BigInt->new($num);
# Get the length (or count of
# digits) of the
# given number using
# Math::BigInt->length() method
$len = $x->length();
# Variable to store first half
$firstHalf = 0;
$i = 1;
# loop to calculate first half
while($i <= ($len/2))
{
$firstHalf = ($firstHalf * 10) +
$x->digit(-$i);
$i = $i + 1;
}
# Variable to store second half
$secondHalf = 0;
# Loop to calculate second half
while($i <= $x->length())
{
$secondHalf = ($secondHalf * 10) +
$x->digit(-$i);
$i = $i + 1;
}
# Note: Math::BigInt->digit() method
# returns the digit at ith position
# from right end of the given number
# a negative value of i is used
# to get ith digit from left end
# of the given number
# Print original number
print "Original number: $num\n";
# Print first half
print "First half: $firstHalf\n";
# Print Second half
print "Second half: $secondHalf";
输出:
Original number: 78215936043546
First half: 7821593
Second half: 6043546