Take a positive integer X. This number is part of the sequence we are interested in if the sum of all digits of X is a divisor of X, and if the product of all digits of X is a divisor of X.

For example, 135 is such a number because 1 + 3 + 5 = 9 which divides 135 = 9 * 15 and 1 * 3 * 5 = 15 which also divides 135.

This is sequence A038186 in the OEIS.

Your task: given an integer N, output the Nth positive integer with such properties.

Inputs and outputs

  • Numbers may be 0-indexed or 1-indexed; please indicate which one your answer use.

  • The input may be taken through STDIN, as a function argument, or anything similar.

  • The output may be printed to STDOUT, returned from a function, or anything similar.

Test cases

The test cases below are 1-indexed.

Input        Output

1            1
5            5
10           12
20           312
42           6912
50           11313


This is , so the shortest answer in bytes wins.

  • \$\begingroup\$ would it be ok to print out each number as you calculate it up towards n=infinity? \$\endgroup\$
    – Blue
    Nov 29, 2016 at 9:36
  • \$\begingroup\$ @BlueEyedBeast No, you have to take an input and return the corresponding number. \$\endgroup\$
    – Fatalize
    Nov 29, 2016 at 9:37
  • \$\begingroup\$ When checking 10, is the product of its digits 0 or 1? \$\endgroup\$
    – george
    Nov 29, 2016 at 14:06
  • 2
    \$\begingroup\$ @george its product is 0. \$\endgroup\$
    – Fatalize
    Nov 29, 2016 at 14:20
  • \$\begingroup\$ Can I arbitrarily limit the range of the input if the upper limit of the range wouldn't be computed before the heat death of the universe anyways? \$\endgroup\$
    – cat
    Dec 1, 2016 at 13:44

34 Answers 34


BASH, 125 bytes

while ((n<$1));do
p(){ fold -1<<<$i|paste -sd$1|bc;}
z=`p \*`
((z))&&[ $[i%`p +`]$[i%z] -eq 0 ]&&((n++))
echo $i

Perl 5 -MList::Util=sum,product -p, 63 bytes

($\%sum(@a=++$\=~/./g)+$\=~/0/||$\%product@a)&&redo for 1..$_}{

Try it online!



Jelly, 11 bytes


Try it online!


          Ṫ  get the last element after
        µ#   counting the first (input) elements where
       Ạ     all (both) are true:
     ḍ¹      the element is divisible by
 S,P         the sum, and the products of
D            the digits

Julia, 72 bytes

n->(i=c=1;while c<n d=digits(i+=1);c+=i%sum(d)<all(d.>0)>i%prod(d)end;i)

Try it online!

improvement over Alex A's answer (explanation there)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.