Skip to content

Commit 7fa8cea

Browse files
committed
find smallest number whose digits_product is equal to given number
1 parent c692c24 commit 7fa8cea

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

beginners/digits_product.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
2+
# Given an integer product, find the smallest positive integer the product of whose digits is equal to given product. If there is no such integer, return -1 instead.
3+
4+
def digits_product(product)
5+
digits=[]
6+
if product<10
7+
return product+10
8+
end
9+
9.downto(2).each do |i| #find all factors starting from 9 down to 2 and then reverse them to get the smallest positive integer whose digit's product is equal to the given number
10+
while product%i == 0
11+
digits<<i
12+
product=product/i
13+
end
14+
end
15+
if product > 10 #means given number has a prime factor greater than 10.
16+
return -1
17+
end
18+
digits.reverse.join
19+
end
20+
21+
print digits_product(100)
22+
puts ""
23+
print digits_product(1000)

0 commit comments

Comments
 (0)