VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-calculate-product-of-digits-of-a-number/

⇱ Program to calculate product of digits of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to calculate product of digits of a number

Last Updated : 13 Mar, 2023

Given a number, the task is to find the product of the digits of a number.

Examples: 

Input: n = 4513
Output: 60

Input: n = 5249
Output: 360

General Algorithm for product of digits in a given number:  

  1. Get the number
  2. Declare a variable to store the product and set it to 1
  3. Repeat the next two steps till the number is not 0
  4. Get the rightmost digit of the number with help of remainder '%' operator by dividing it with 10 and multiply it with product.
  5. Divide the number by 10 with help of '/' operator
  6. Print or return the product.

Below is the solution to get the product of the digits: 


Output
60

Time Complexity: O(log10N)
Auxiliary Space: O(1)

Method #2:Using string() method:

  • Convert the integer to string
  • Traverse the string and multiply the characters by converting them to integer

When this method can be used?: When the number of digits of a number exceeds  , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)

Below is the implementation:


Output
60

Time Complexity: O(N)
Auxiliary Space: O(1)

Method #3: Recursion

  1. Get the number
  2.  Get the remainder and pass the next remaining digits
  3. Get the rightmost digit of the number with help of the remainder '%' operator by dividing it by 10 and multiply it to the product.
  4.   Divide the number by 10 with help of '/' operator to remove the rightmost digit
  5.  Check the base case with n = 0
  6. Print or return the product

Output
10

Time Complexity: O(log10N)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: