Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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




#!/usr/bin/perl 
  
# Import Math::BigInt module
use Math::BigInt;
  
$num = 7821593604;
  
# Create a BigInt object
$x = Math::BigInt->new($num);
  
# Initialize n
$n = 4;
  
# Get the nth digit
# counting from right side 
$nth_digit = $x->digit($n);
  
print "${n}th digit in $num is $nth_digit.\n";
  
# Assign new value to n
$n = 6;
  
# Get the nth digit 
# counting from right side
$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




#!/usr/bin/perl 
  
# Import Math::BigInt module
use Math::BigInt;
  
$num = 7821593604;
  
# Create a BigInt object
$x = Math::BigInt->new($num);
  
# To get nth digit form 
# left side of the number
# we need to specify n 
# as a negative number 
  
# If n is negative then 
# then method will return
# nth digit from left side
# but counting will start from 1.
  
# Initialize n
$n = 4;
  
# Get the nth digit
# from left side 
$nth_digit = $x->digit(-$n);
  
print "${n}th digit from left in $num is $nth_digit.\n";
  
# Assign new value to n
$n = 6;
  
# Get the nth digit 
# counting from left side
$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




#!/usr/bin/perl 
  
# Import Math::BigInt module
use Math::BigInt;
  
$num = 7821593604;
  
# Create a BigInt object
$x = Math::BigInt->new($num);
  
# Get the length of the number
$length = $x->length();
  
# Variable to store sum
$sum = 0;
  
# for loop to calculate 
# sum of digits in given number
for($i = 0; $i < $length; $i++)
{
    # Get the ith digit from the
    # right side of the number 
    $sum = $sum + $x->digit($i);
  
}
  
# Print sum
print "Sum of digits in $num is $sum.";
Output:
Sum of digits in 7821593604 is 45.



My Personal Notes arrow_drop_up
Recommended Articles
Page :