
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Largest product of contiguous digits in Python
Suppose we have two numbers num and k, we have to find the largest product of k contiguous digits in num. We have to keep in mind that num is guaranteed to have >= k digits.
So, if the input is like num = 52689762 and k = 4, then the output will be 3024, largest product of 4 consecutive digits is (8*9*7*6) = 3024.
To solve this, we will follow these steps −
- largest := 0
- cand := 1
- while (quotient of num/10)^(k-1) > 0, do
- digits := (last digit of nums)^k
- cand := 1
- while digits > 0, do
- cand := cand * (digits mod 10)
- if cand is same as 0, then
- come out from the loop
- digits := quotient of digits / 10
- largest := maximum of largest and cand
- num := quotient of nums / 10
- return largest
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, num, k): largest = 0 while num // 10 ** (k - 1) > 0: digits = num % 10 ** k cand = 1 while digits > 0: cand *= digits % 10 if cand == 0: break digits //= 10 largest = max(largest, cand) num //= 10 return largest ob = Solution() num = 52689762 k = 4 print(ob.solve(num,k))
Input
52689762, 4
Output
3024
- Related Articles
- Largest product of n contiguous digits of a number in JavaScript
- Program to find maximum product of contiguous subarray in Python
- Largest Sum Contiguous Subarray
- C/C++ Program for Largest Sum Contiguous Subarray?
- Program to find largest product of three unique items in Python
- Program to find the largest product of two distinct elements in Python
- Largest Palindrome Product in C++
- Finding product of Number digits in JavaScript
- Recursive product of summed digits JavaScript
- Python - Contiguous Boolean Range
- Find the Largest number with given number of digits and sum of digits in C++
- Largest Time for Given Digits in C++
- Largest number with prime digits in C++
- Python - Group contiguous strings in List
- Check whether product of digits at even places is divisible by sum of digits at odd place of a numbers in Python

Advertisements