Header Ad

HackerEarth A smallest number problem solution

In this HackerEarth A smallest number problem solution You are given an integer K.

Find the smallest number N such that  has exactly K digits and none of the digits in N is $$0$$. Also, the product of digits in number N is greater than or equal to the sum of digits in number N.


HackerEarth A smallest number problem solution


HackerEarth A smallest number problem solution.

#include<bits/stdc++.h>
#define int long long int
using namespace std;
int sum, product;

int get_digits(int num)
{
int answer = 0;
while(num)
{
num /= 10;
answer++;
}
return answer;
}

bool check(int num)
{
sum = 0;
product = 1;
while(num)
{
sum += (num%10);
product *= (num%10);
num /= 10;
}

return (product >= sum);
}

void solve(){
int k;
cin >> k;
assert(1 <= k and k <= 500000);

if(k <= 6)
{
for(int i = 1 ; i < 1000000 ; i++){
if(check(i) and get_digits(i) == k)
{
cout << i << endl;
return;
}
}
}
else{
for(int i = 1 ; i < 1000000 ; i++){
check(i);
if(product >= sum + k - get_digits(i))
{
for(int j = 1 ; j <= (k - get_digits(i)) ; j++){
cout << 1;
}
cout << i << endl;
return;
}
}
}
}
signed main(){
int t;
cin >> t;
assert(1 <= t and t <= 10);
while(t--){
solve();
}
}

Second solution

def multiplyList(myList):
# Multiply elements one by one
result = 1
for x in myList:
result = result * x
return result


t = int(input())
while t > 0:
t -= 1
n = int(input())
for i in range(1, 10 ** 6):
if '0' not in str(i) and multiplyList(map(int, str(i))) >= n - len(str(i)) + sum(map(int, str(i))):
print('1' * (n - len(str(i))), i, sep='')
break


Post a Comment

0 Comments