UVA 993 Product of digits Solution

Smallest number k such that the product of digits of k is equal to n


Given a non-negative number n. The problem is to find the smallest number k such that the product of digits of k is equal to n. If no such number k can be formed then print “-1”.
Approach: For each i = 9 to 2, repeatedly divide n by i until it cannot be further divided or the list of numbers from 9 to 2 gets finished. Also, in the process of division push each digit i onto the stack which divides n completely. After the above process gets completed check whether n == 1 or not. If not, then print “-1”, else form the number k using the digits from the stack containing the digits in the same sequence as popped from the stack.
Solution in c++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include <bits/stdc++.h>
using namespace std;
long long int smallestNumber(int n)
{
    if (n >= 0 && n <= 9)
        return n;
    stack<int> digits;
    for (int i=9; i>=2 && n > 1; i--)
    {
        while (n % i == 0)
        {
            digits.push(i);
            n = n / i;
        }
    }
    if (n != 1)
        return -1;
    long long int k = 0;
    while (!digits.empty())
    {
        k = k*10 + digits.top();
        digits.pop();
    }
    return k;
}

int main()
{
    int n,t,l ;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cout << smallestNumber(n)<<endl;
    }
    return 0;

}

No comments

Most View Post

Recent post

Codeforces Round 971 (Div. 4) 2009C. The Legend of Freya the Frog Solution

  Problem Link    https://codeforces.com/contest/2009/problem/C S olution in C++: /// Author : AH_Tonmoy #include < bits / stdc ++. h &g...

Powered by Blogger.