Perl | Math::BigInt->length() method
Math::BigInt
module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.
length()
method of Math::BigInt
module is used to get the length of the given number i.e the count of digits in the given number.
Syntax: Math::BigInt->length()
Parameter: None
Returns: an integer value which represents the length of the given number.
Example 1: Use of Math::BigInt->length()
method to count digits in a number
use Math::BigInt;
$num = 78215936043546;
$x = Math::BigInt->new( $num );
$len = $x -> length ();
print "Length of $num is $len.\n" ;
$num = 7821593604584625197;
$x = Math::BigInt->new( $num );
$len = $x -> length ();
print "Length of $num is $len.\n" ;
|
Output:
Length of 78215936043546 is 14.
Length of 7821593604584625197 is 19.
Example 2: Use of Math::BigInt->length()
method to split a given number into two halves.
use Math::BigInt;
$num = 78215936043546;
$x = Math::BigInt->new( $num );
$len = $x -> length ();
$firstHalf = 0;
$i = 1;
while ( $i <= ( $len /2))
{
$firstHalf = ( $firstHalf * 10) +
$x ->digit(- $i );
$i = $i + 1;
}
$secondHalf = 0;
while ( $i <= $x -> length ())
{
$secondHalf = ( $secondHalf * 10) +
$x ->digit(- $i );
$i = $i + 1;
}
print "Original number: $num\n" ;
print "First half: $firstHalf\n" ;
print "Second half: $secondHalf" ;
|
Output:
Original number: 78215936043546
First half: 7821593
Second half: 6043546
Last Updated :
03 Oct, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...