Perl | Math::BigInt->digit() method
Last Updated :
26 Sep, 2019
Math::BigInt
module in Perl provides objects that represent integers with arbitrary precision and overloaded arithmetical operators.
digit()
method of Math::BigInt
module is used to get nth digit of the given number counting from right. To get the digit from the left side we need to specify n as negative.
Syntax: Math::BigInt->digit($n)
Parameter:
$n: An integer value denoting the digit to be extracted.
Returns: an integer value which represents the nth digit of the given number counting from the right side.
Example 1: use of Math::BigInt->digit()
method
use Math::BigInt;
$num = 7821593604;
$x = Math::BigInt->new( $num );
$n = 4;
$nth_digit = $x ->digit( $n );
print "${n}th digit in $num is $nth_digit.\n" ;
$n = 6;
$nth_digit = $x ->digit( $n );
print "${n}th digit in $num is $nth_digit.\n" ;
|
Output:
4th digit in 7821593604 is 9.
6th digit in 7821593604 is 1.
Example 2: use of Math::BigInt->digit()
method to get nth digit from left
use Math::BigInt;
$num = 7821593604;
$x = Math::BigInt->new( $num );
$n = 4;
$nth_digit = $x ->digit(- $n );
print "${n}th digit from left in $num is $nth_digit.\n" ;
$n = 6;
$nth_digit = $x ->digit(- $n );
print "${n}th digit from left in $num is $nth_digit.\n" ;
|
Output:
4th digit from left in 7821593604 is 1.
6th digit from left in 7821593604 is 9.
Example 3: use of Math::BigInt->digit()
method to calculate sum of digits of a number
use Math::BigInt;
$num = 7821593604;
$x = Math::BigInt->new( $num );
$length = $x -> length ();
$sum = 0;
for ( $i = 0; $i < $length ; $i ++)
{
$sum = $sum + $x ->digit( $i );
}
print "Sum of digits in $num is $sum." ;
|
Output:
Sum of digits in 7821593604 is 45.
Share your thoughts in the comments
Please Login to comment...