Find the number in a range having maximum product of the digits

Given a range represented by two positive integers L and R. Find the number lying in the range having the maximum product of the digits.

Examples:

Input : L = 1, R = 10
Output : 9

Input : L = 51, R = 62
Output : 59

Approach : The key idea here is to iterate over the digits of the number R starting from the most significant digit. Going from left to right, i.e. from most sigificant digit to the least significant digit, replace the current digit with one less than current digit and replace all the digits after current digit in the number with 9, since the number has already become smaller than R at the current position so we can safely put any number in the following digits to maximize the product of digits. Also, check if the resulting number is greater than L to remain in the range and update the maximum product.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find the number in a
// range having maximum product of the
// digits
  
#include <bits/stdc++.h>
using namespace std;
  
// Returns the product of digits of number x
int product(int x)
{
    int prod = 1;
    while (x) {
        prod *= (x % 10);
        x /= 10;
    }
    return prod;
}
  
// This function returns the number having
// maximum product of the digits
int findNumber(int l, int r)
{
    // Converting both integers to strings
    string a = to_string(l);
    string b = to_string(r);
  
    // Let the current answer be r
    int ans = r;
    for (int i = 0; i < b.size(); i++) {
        if (b[i] == '0')
            continue;
  
        // Stores the current number having
        // current digit one less than current
        // digit in b
        string curr = b;
        curr[i] = ((curr[i] - '0') - 1) + '0';
  
        // Replace all following digits with 9
        // to maximise the product
        for (int j = i + 1; j < curr.size(); j++)
            curr[j] = '9';
  
        // Convert string to number
        int num = 0;
        for (auto c : curr)
            num = num * 10 + (c - '0');
  
        // Check if it lies in range and its product
        // is greater than max product
        if (num >= l && product(ans) < product(num))
            ans = num;
    }
  
    return ans;
}
  
// Driver Code
int main()
{
    int l = 1, r = 10;
    cout << findNumber(l, r) << endl;
  
    l = 51, r = 62;
    cout << findNumber(l, r) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find the number in a
// range having maximum product of the
// digits
  
class GFG
{
      
// Returns the product of digits of number x
static int product(int x)
{
    int prod = 1;
    while (x > 0
    {
        prod *= (x % 10);
        x /= 10;
    }
    return prod;
}
  
// This function returns the number having
// maximum product of the digits
static int findNumber(int l, int r)
{
    // Converting both integers to strings
    //string a = l.ToString();
    String b = Integer.toString(r);
  
    // Let the current answer be r
    int ans = r;
    for (int i = 0; i < b.length(); i++) 
    {
        if (b.charAt(i) == '0')
            continue;
  
        // Stores the current number having
        // current digit one less than current
        // digit in b
        char[] curr = b.toCharArray();
        curr[i] = (char)(((int)(curr[i] - 
                    (int)'0') - 1) + (int)('0'));
  
        // Replace all following digits with 9
        // to maximise the product
        for (int j = i + 1; j < curr.length; j++)
            curr[j] = '9';
  
        // Convert string to number
        int num = 0;
        for (int j = 0; j < curr.length; j++)
            num = num * 10 + (curr[j] - '0');
  
        // Check if it lies in range and its product
        // is greater than max product
        if (num >= l && product(ans) < product(num))
            ans = num;
    }
  
    return ans;
}
  
// Driver Code
public static void main (String[] args) 
{
    int l = 1, r = 10;
    System.out.println(findNumber(l, r));
  
    l = 51;
    r = 62;
    System.out.println(findNumber(l, r));
}
}
  
// This code is contributed by chandan_jnu

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to find the number 
# in a range having maximum product 
# of the digits 
  
# Returns the product of digits
# of number x 
def product(x) : 
      
    prod = 1
    while (x) :
        prod *= (x % 10
        x //= 10
      
    return prod
  
# This function returns the number having 
# maximum product of the digits 
def findNumber(l, r) :
      
    # Converting both integers to strings 
    a = str(l); 
    b = str(r); 
  
    # Let the current answer be r 
    ans = r
      
    for i in range(len(b)) : 
        if (b[i] == '0') : 
            continue
  
        # Stores the current number having 
        # current digit one less than current 
        # digit in b 
        curr = list(b)
        curr[i] = str(((ord(curr[i]) - 
                        ord('0')) - 1) + ord('0'))
  
        # Replace all following digits with 9 
        # to maximise the product 
        for j in range(i + 1, len(curr)) :
            curr[j] = str(ord('9'))
              
        # Convert string to number 
        num = 0
        for c in curr :
            num = num * 10 + (int(c) - ord('0')) 
  
        # Check if it lies in range and its
        # product is greater than max product 
        if (num >= l and product(ans) < product(num)) :
            ans = num
  
    return ans
  
# Driver Code 
if __name__ == "__main__" :
      
    l, r = 1, 10
    print(findNumber(l, r))
  
    l, r = 51, 62
    print(findNumber(l, r))
  
# This code is contributed by Ryuga

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find the number in a
// range having maximum product of the
// digits
using System;
  
class GFG
{
      
// Returns the product of digits of number x
static int product(int x)
{
    int prod = 1;
    while (x > 0) 
    {
        prod *= (x % 10);
        x /= 10;
    }
    return prod;
}
  
// This function returns the number having
// maximum product of the digits
static int findNumber(int l, int r)
{
    // Converting both integers to strings
    //string a = l.ToString();
    string b = r.ToString();
  
    // Let the current answer be r
    int ans = r;
    for (int i = 0; i < b.Length; i++) 
    {
        if (b[i] == '0')
            continue;
  
        // Stores the current number having
        // current digit one less than current
        // digit in b
        char[] curr = b.ToCharArray();
        curr[i] = (char)(((int)(curr[i] - 
                    (int)'0') - 1) + (int)('0'));
  
        // Replace all following digits with 9
        // to maximise the product
        for (int j = i + 1; j < curr.Length; j++)
            curr[j] = '9';
  
        // Convert string to number
        int num = 0;
        for (int j = 0; j < curr.Length; j++)
            num = num * 10 + (curr[j] - '0');
  
        // Check if it lies in range and its product
        // is greater than max product
        if (num >= l && product(ans) < product(num))
            ans = num;
    }
  
    return ans;
}
  
// Driver Code
static void Main()
{
    int l = 1, r = 10;
    Console.WriteLine(findNumber(l, r));
  
    l = 51;
    r = 62;
    Console.WriteLine(findNumber(l, r));
}
}
  
// This code is contributed by chandan_jnu

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find the number 
// in a range having maximum product 
// of the digits 
  
// Returns the product of digits
// of number x 
function product($x)
    $prod = 1;
    while ($x)
    {
        $prod *= ($x % 10); 
        $x = (int)($x / 10);
    }
      
    return $prod;
}
  
// This function returns the number 
// having maximum product of the digits 
function findNumber($l, $r)
{
    // Let the current answer be r 
    $ans = $r;
      
    // Converting both integers
    // to strings 
    $a = strval($l); 
    $b = strval($r); 
  
    for ($i = 0; $i < strlen($b); $i++)
    
        if ($b[$i] == '0')
            continue;
  
        // Stores the current number having 
        // current digit one less than 
        // current digit in b 
        $curr = $b;
        $curr[$i] = chr(((ord($curr[$i]) - 
                          ord('0')) - 1) + 
                          ord('0'));
  
        // Replace all following digits 
        // with 9 to maximise the product 
        for ($j = $i + 1; $j < strlen($curr); $j++)
            $curr[$j] = '9';
              
        // Convert string to number 
        $num = 0;
        for ($c = 0; $c < strlen($curr); $c++)
            $num = $num * 10 + (ord($curr[$c]) - 
                                ord('0')); 
  
        // Check if it lies in range and its
        // product is greater than max product 
        if ($num >= $l and 
            product($ans) < product($num))
            $ans = $num;
    }
  
    return $ans;
}
  
// Driver Code 
$l = 1; 
$r = 10;
print(findNumber($l, $r) . "\n");
  
$l = 51;
$r = 62;
print(findNumber($l, $r));
  
// This code is contributed
// by chandan_jnu
?>

chevron_right


Output:

9
59

Time Complexity: O(18 * 18), if we are dealing with the numbers upto 1018.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01, Chandan_Kumar