Minimum Factorization in C++


Suppose we have a positive integer x, we have to find the smallest positive integer b whose multiplication of each digit equals to x. If we have no such answer then return 0.

So, if the input is like 48, then the output will be 68

To solve this, we will follow these steps −

  • ret := 0, mul := 1

  • if a < 2, then:

    • return a

  • for initialize i := 9, when i >= 2, update (decrease i by 1), do −

    • while a mod i is same as 0, do −

      • ret := i * mul + ret

      • mul := mul * 10

      • a := a / i

  • return (if a < 2 and ret < inf, then ret, otherwise 0)

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int smallestFactorization(int a) {
      lli ret = 0;
      lli mul = 1;
      if (a < 2)
         return a;
      for (lli i = 9; i >= 2; i--) {
         while (a % i == 0) {
            ret = i * mul + ret;
            mul *= 10;
            a /= i;
         }
      }
      return a < 2 && ret < INT_MAX ? ret : 0;
   }
};
main(){
   Solution ob;
   cout << (ob.smallestFactorization(48));
}

Input

48

Output

68

Updated on: 16-Nov-2020

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements