4
$\begingroup$

My aim is to generate a list of integers less than a given value $r$ with their digit sum equal to $s$.

My code given below works fine but it is slow. I would like to see efficient versions.

f[r_,s_]:=Select[Range[r], Total[IntegerDigits[#]] == s &]
$\endgroup$
2
  • $\begingroup$ What is $s$ representing in your code? Is that $k$? Looks like it, but checking... $\endgroup$
    – MikeY
    Commented Dec 14, 2018 at 20:34
  • $\begingroup$ @MikeY Thanks for pointing that out. I will update the question. $\endgroup$ Commented Dec 15, 2018 at 3:48

1 Answer 1

7
$\begingroup$

We can work backwards so to speak:

f[r_, s_] := Union[Select[
  FromDigits /@ Join @@ Permutations /@ IntegerPartitions[s, Ceiling[Log10[r]], Range[0, 9]], 
  LessThan[r]
]]

Example:

f[1000, 6]
{6, 15, 24, 33, 42, 51, 60, 105, 114, 123, 132, 141, 150, 204, 213, 222, 231, 240, 303, 312, 321, 330, 402, 411, 420, 501, 510, 600}
Total[IntegerDigits[f[1000, 6]], {2}]
{6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}

Larger example:

vals = f[10^12, 100]; // AbsoluteTiming
{0.069749, Null}
Length[vals]
75582

Verify:

Total[IntegerDigits[vals], {2}] // Union
{100}
$\endgroup$
4
  • $\begingroup$ Thanks. But, I noticed that for f[1000,1] returns me only {1}, instead of {1,10,100}. $\endgroup$ Commented Dec 14, 2018 at 20:10
  • $\begingroup$ @Expikx Documentation details for IntegerPartitions shows it defaults to using numbers > 0. Change his Range[9] to Range[0,9] and it will include 10 and 100 in the results for f[1000,1]. Perhaps that will give you what you are looking for. $\endgroup$
    – Bill
    Commented Dec 14, 2018 at 21:16
  • $\begingroup$ @Bill thanks for pointing that out. I've updated my solution. $\endgroup$
    – Greg Hurst
    Commented Dec 14, 2018 at 21:46
  • $\begingroup$ @Bill That fixed it. Thanks. $\endgroup$ Commented Dec 15, 2018 at 3:49

Your Answer

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

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