23
\$\begingroup\$

A digit addition generator of an integer n is any integer x that satisfy the equation x + s(x) = n, with s(x) being the sum of the digits of x. (We will work under base 10 for convenience.)

For example, a digit addition generator for 29 would be 19, because 19 + (1 + 9) = 29. Some numbers have more than one generator. An example might be 216, which has generators of 198 and 207.

Your objective is to generate the sequence a_n where a_i is the lowest digit addition generator of every non-negative integer i, and anything other than a non-negative integer if there is none for i. The non-negative terms in your result should match the sequence A096234. You may find this paper related to the challenge.

Fewest bytes win; standard rules apply.

\$\endgroup\$
5
  • \$\begingroup\$ If there is no solution, is it acceptable to loop forever without output, or do we need to terminate? \$\endgroup\$
    – xnor
    Jun 15 at 8:31
  • \$\begingroup\$ @xnor That's okay. \$\endgroup\$ Jun 15 at 8:41
  • \$\begingroup\$ Presumably the expected output for 0 is 0? \$\endgroup\$
    – Shaggy
    Jun 15 at 14:09
  • \$\begingroup\$ @Shaggy Yes. 0 + (0) is indeed 0 \$\endgroup\$ Jun 15 at 16:12
  • \$\begingroup\$ Just making sure that x<=n and not just x<n. Perhaps you could add n=0 to the challenge as a test case, along with a few others, as a few of us did get tripped up by it. \$\endgroup\$
    – Shaggy
    Jun 15 at 22:31

28 Answers 28

5
\$\begingroup\$

Vyxal gM, 28 bitsv2, 3.5 bytes

'∑+?=

Try it Online!

Outputs an empty list for no result. I think (spoiler I did) I ninja'd someone in the process of writing this lol.

Explained

'∑+?=
'      # filter the range [0, n] by:
 ∑+    #   sum of digits + x
   ?=  #   equals input? 
# g flag prints minimum. 
\$\endgroup\$
1
  • \$\begingroup\$ Lol, I've been ninja'd \$\endgroup\$ Jun 15 at 9:14
5
\$\begingroup\$

05AB1E, 7 bytes

Ý.ΔDªOQ

Outputs -1 if there is no result.

Try it online or verify a few more test cases.

Explanation:

Ý        # Push a list in the range [0, (implicit) input-integer]
 .Δ      # Find the first value of this list that's truthy for, or -1 if none are:
   D     #  Duplicate the current value
    ª    #  Convert the first value to a list of digits,
         #  and append the duplicated number to this list
     O   #  Sum the list together
      Q  #  Check whether it's equal to the (implicit) input-integer
         # (after which the result is output implicitly)
\$\endgroup\$
2
  • \$\begingroup\$ That was quick! \$\endgroup\$ Jun 15 at 8:40
  • 4
    \$\begingroup\$ @TomEpsilon Could have been quicker if I saw the challenge 10 minutes earlier. ;) Nice first challenge btw, and welcome to CGCC! \$\endgroup\$ Jun 15 at 8:41
4
\$\begingroup\$

PARI/GP, 44 bytes

f(n,i)=if(i>n,x,i+sumdigits(i)-n,f(n,i+1),i)

Attempt This Online!

Returns x when there is no solution.

\$\endgroup\$
4
\$\begingroup\$

Japt, 8 bytes

Outputs -1 for no result.

ôÈ+ìxÃbU

Try it

(Eventually) outputs undefined for no result.

@¶X+ìx}a

Try it

ôÈ+ìxÃbU     :Implicit input of integer U
ô            :Range [0,U]
 È           :Pass each through the following function
  +          :  Add
   ì         :  Convert to digit array
    x        :  Reduce by addition
     Ã       :End function
      bU     :First 0-based index of U
@¶X+ìx}a     :Implicit input of integer U
@            :Function taking an integer X as argument
 ¶           :  Test U for equality with
  X+         :    Add to X
    ì        :      Convert X to digit array
     x       :      Reduce by addition
      }      :End function
       a     :Get the first integer >=0 that returns true
\$\endgroup\$
5
  • \$\begingroup\$ Yup, your second version is what I came up with as well. (This is Jacob, I changed my username) \$\endgroup\$
    – noodle man
    Jun 15 at 12:22
  • 1
    \$\begingroup\$ 6 bytes +ìx ¥N \$\endgroup\$
    – noodle man
    Jun 15 at 12:43
  • \$\begingroup\$ Came up with the exact same while I was out to lunch, @noodleman :) Do you want to run with it before I edit it into mine? \$\endgroup\$
    – Shaggy
    Jun 15 at 13:44
  • \$\begingroup\$ Scratch that, @noodleman; it fails for 0. \$\endgroup\$
    – Shaggy
    Jun 15 at 14:08
  • \$\begingroup\$ I think I can add the x flag, which does nothing for regular outputs and throws an error for undefined, i.e. empty output, and "" == 0. I'm going to post my version now. \$\endgroup\$
    – noodle man
    Jun 15 at 15:37
4
\$\begingroup\$

APL (Dyalog Extended), 21 bytes

Anoymous tacit prefix function. Requires 0-indexing (⎕IO←0).

⍸⊢<\⍤=0,⍨⍳+1⊥¨⍎¨∘⍕¨∘⍳

Try it online!

 where do we find that

 the argument

<\ is the first (lit. cum. right-ass. less red.)

 that:

= equals

0,⍨ zero appended to

 the range

+ plus

1⊥ the sum (lit. base-1 eval.)

¨ of each of

 the evaluation

¨ of each

 of:

 the stringification

¨ of each

 of:

   the range

\$\endgroup\$
2
  • 8
    \$\begingroup\$ I’m sorry, but what does “ lit. cum. right-ass. less red.” mean? \$\endgroup\$ Jun 15 at 11:25
  • 2
    \$\begingroup\$ @TomEpsilon literally cumulative right-associative less reduction \$\endgroup\$
    – Adám
    Jun 15 at 12:02
4
\$\begingroup\$

C (clang), 58 bytes

loops forever if there's no solution

d,s;f(*i,n){for(*i=s=0;n-s;)for(s=d=++*i;d;d/=10)s+=d%10;}

Try it online!

C (clang), 70 bytes

For comparison, this returns negative values when there's no solution.

g,o,l;f(*i,n){for(*i=g=-n;g++;*i=n+l?*i:-g)for(l=o=g;o;o/=10)l+=o%10;}

Try it online!

\$\endgroup\$
4
\$\begingroup\$

C++ (gcc), 71 \$\cdots\$ 66 64 bytes

[](int&n){for(int m=n,d=n=0,t;m-d;)for(d=t=++n;t;t/=10)d+=t%10;}

Try it online!

Saved 6 bytes thanks to c--!!!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ @c-- Nice one - thanks! :D \$\endgroup\$
    – Noodle9
    Jun 16 at 10:06
  • 1
    \$\begingroup\$ @c-- Very good - thanks! :D \$\endgroup\$
    – Noodle9
    Jun 22 at 20:40
3
\$\begingroup\$

JavaScript, 49 bytes

Loops forever, in theory, if there's no result but, in practice, throws a recursion error.

n=>(g=x=>n-eval([x,...x+``].join`+`)?g(++x):x)`0`

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

Raku, 34 bytes

{first 0..$^n: {$_+.comb.sum==$n}}

Try it online!

Returns the first element of the range 0 through the input number $^n/$n such that the element $_ plus the sum of its digits .comb.sum is equal to the input number. If there is no such number, Nil is returned.

\$\endgroup\$
3
\$\begingroup\$

R, 45 46 bytes

Edit: +1 byte to correctly handle input of zero, but then -1 byte thanks pajonk for removal of useless accidental space

\(n){while(n-F-sum(F%/%10^(0:F)%%10))F=F+1;+F}

Attempt This Online!

Tests increasing integers until it finds a solution, so loops forever if no solution exists.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You have an extra space at the start of you code... \$\endgroup\$
    – pajonk
    Jun 15 at 17:57
  • \$\begingroup\$ @pajonk - Ah, thanks v much for spotting that! \$\endgroup\$ Jun 15 at 18:16
3
\$\begingroup\$

Pyth, 8 bytes

x|msajdT

Try it online!

Returns -1 for no result.

Explanation

x|msajdTdQQQ    # implicitly add dQQQ
                # implicitly assign Q = eval(input())
  m      Q      # map lambda d over range(Q):
     jdT        #   list the digits of d
    a   d       #   append d to this list
   s            #   sum the list
 |        Q     # short circuiting or, does nothing unless the input is 0, then [] -> 0
x          Q    # find the first index of Q in the mapped list (or xors with 0 for 0), returns -1 if not found

\$\endgroup\$
2
  • \$\begingroup\$ Input 0 also yields -1, which is untrue (should have been 0). I apologize if this might cause non-alphabetical issues. \$\endgroup\$ Jun 15 at 16:54
  • 1
    \$\begingroup\$ @TomEpsilon My bad, did not realize I needed to account for 0. And indeed it has :( but even worse it cost me a byte :((( \$\endgroup\$ Jun 15 at 21:09
3
\$\begingroup\$

Arturo,  40  35 bytes

$->x[0while[x<>+∑digits<=<=]->1+]

Try it!

Causes an infinite loop when there is no result.

$->x[                  ; a function taking an integer x
    0                  ; push 0 to stack
    while[x<>          ; while x doesn't equal...
        <=<=           ; duplicate top of stack twice
        +∑digits       ; digit sum then add
    ]                  ; end while condition
    ->1+               ; increment top of stack (while body)
]                      ; end function
\$\endgroup\$
3
\$\begingroup\$

Elixir, 74 72 bytes

import Enum
c=& &1-?0
r=&find(1..&1,fn x->&1==x+sum map'#{x}',c end)||-1

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Wolfram Language (Mathematica), 89 53 49 44 bytes

#&@@Pick[r=Range@#,r+Tr/@IntegerDigits@r,#]&

Try it online!

Thanks to @ovs and @att!

\$\endgroup\$
4
  • \$\begingroup\$ That was hell of an optimization. \$\endgroup\$ Jun 15 at 8:56
  • \$\begingroup\$ Sure it can be more golfed \$\endgroup\$
    – lesobrod
    Jun 15 at 8:58
  • 1
    \$\begingroup\$ 49 bytes with Range[n=#] and Tr instead of Total. \$\endgroup\$
    – ovs
    Jun 15 at 9:54
  • \$\begingroup\$ Cases variants typically are shorter than Select variants when you need the outer argument in the selection function, but here Pick does better still: 43 bytes \$\endgroup\$
    – att
    Jun 16 at 1:00
3
\$\begingroup\$

Julia, 42 37 bytes

~n=argmax(x->x+sum(digits(x))==n,0:n)

Attempt This Online!

-5 bytes thanks to MarcMush: use argmax instead of findfirst

\$\endgroup\$
3
  • \$\begingroup\$ Your TIO doesn't seem to work. \$\endgroup\$
    – Shaggy
    Jun 15 at 22:32
  • \$\begingroup\$ I added an example that prints. Before, I had only been using @assert statements, which will silently pass if the tests succeed. \$\endgroup\$ Jun 16 at 1:27
  • 1
    \$\begingroup\$ with argmax, 41 bytes or 37 bytes with julia 1.7+ \$\endgroup\$
    – MarcMush
    Jun 16 at 18:34
2
\$\begingroup\$

Java, 85 bytes

n->{for(int i=-1;i++<n;)if((i+"").chars().map(d->d-48).sum()+i==n)return i;return-1;}

Outputs -1 if there is no result.

Try it online.

Explanation:

n->{                   // Method with integer as both parameter and return-type
  for(int i=-1;i++<n;) //  Loop `i` in the range (-1,n]:
    if((i+"")          //   Convert `i` to a String
       .chars()        //   Then to an IntStream of codepoints
       .map(d->d-48)   //   Then to an IntStream of digits
       .sum()          //   And sum those digits together
             +i        //   Add integer `i`
               ==n)    //   And if it's equal to input `n`:
      return i;        //    Return `i` as result
  return-1;}           //  If no result is found, return `-1` instead

Using a recursive function which throws a StackOverflowError when there is no result is also 85 bytes:

n->f(n,0)int f(int n,int i){return(i+"").chars().map(d->d-48).sum()+i==n?i:f(n,i+1);}

Try it online.

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 13 bytes

NθI⌊Φ⊕θ⁼θ⁺ιΣι

Try it online! Link is to verbose version of code. Takes i as an input and outputs None if no generator exists. Explanation: Brute force approach.

Nθ              First input as an integer
      θ         First input
     ⊕          Incremented
    Φ           Filter on implicit range
          ι     Current value
         ⁺      Plus
            ι   Current value
           Σ    Digit sum
       ⁼        Equals
        θ       First input
   ⌊            Take the minimum
  I             Cast to string
                Implicitly print

23 bytes for a less inefficient version:

NθI⌊Φ…·⁻θ×⁹Lθθ⁼θ⁺ιΣ⌈⟦⁰ι

Try it online! Link is to verbose version of code. Explanation: Starts checking for generators starting from i minus 9 times the number of digits of i.

28 bytes for a more efficient version:

NθI⌊ΦELθ⁻⁻θ﹪×⁵θ⁹×⁹ι⁼θ⁺ιΣ⌈⟦⁰ι

Try it online! Link is to verbose version of code. Explanation: As above, but only checks for generators which when doubled are equivalent to i modulo 9 (because i equals the generator plus its digit sum but both the generator and the digit sum are equivalent modulo 9) although it actually computes the maximum possible generator by subtracting 5i reduced modulo 9 from i.

\$\endgroup\$
2
\$\begingroup\$

C# (.NET Core), 73 72 bytes

n=>{for(int i=-1;i++<n;)if((i+"").Sum(d=>d-'0')+i==n)return i;return-1;}

Try it online!

This is a C# port of this answer. All the kudos goes to Kevin Cruijssen.

I really like that .NET's sum is taking a lambda to avoid the common map followed by sum!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can remove the space at return-1; like in my Java answer for -1 byte. :) \$\endgroup\$ Jun 16 at 8:45
  • \$\begingroup\$ @KevinCruijssen forgot this one. Thank you! \$\endgroup\$
    – aloisdg
    Jun 16 at 17:05
2
\$\begingroup\$

Python 3, 63 bytes

g=lambda n:min(x for x in range(n)if x+sum(map(int,str(x)))==n)

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$ Jun 20 at 21:15
2
\$\begingroup\$

Python 3, 56 bytes

f=lambda n,o=0:(o+sum(map(int,str(o)))==n)*o or f(n,o+1)

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Jun 20 at 23:23
  • \$\begingroup\$ o*(...)or f(... saves a byte. \$\endgroup\$ Jul 17 at 15:24
1
\$\begingroup\$

Fig, \$11\log_{256}(96)\approx\$ 9.054 bytes

[KFax'=#x+S

Try it online!

[            # The first item from
   a         # the range from 1 to
    x        # the input,
  F  '       # filtered by:
          S  #   the digit sum of n
         +   #   plus n
      =      #   is equal to
       #x    #   the program's input,
 K           # sorted (smallest to largest).
\$\endgroup\$
1
\$\begingroup\$

Swift, 84  80 bytes

{n in(0...n).map{($0,"\($0)".reduce($0){$0+$1.hexDigitValue!})}.first{$1==n}!.0}

Takes an Int in and returns an Int.

Try it online!

Ungolfed:

{ (n: Int) -> Int in
  (0...n) // a sequence of all integers from 0 to n, inclusive
    // the parens are needed to avoid parsing as 0...(n.map)
    .map { i in // transform each one
      ( // return a tuple of:
        i, // 0. the integer itself
        "\(i)".reduce(i) { $0 + $1.hexDigitValue! } // 1. the digit sum plus the number
        // technically, wholeNumberValue would be more correct than hexDigitValue
      )
    }
    .first { $1 == n }! // find the first one where the sum is the input
    .0 // and return the number that gave that sum
}
\$\endgroup\$
1
\$\begingroup\$

Perl 5 -MList::Util=sum -pa, 29 bytes

$_=0;$_++while"@F"-sum$_,/./g

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Desmos, 66 bytes

I=[0...n]
f(n)=I[[i+∑_{k=0}^imod(floor(i/10^k),10)fori=I]=n].min

Returns undefined if no solution exists.

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
1
\$\begingroup\$

Ruby, 46 bytes

1.step{|c|p (1..c).find{|x|x+x.digits.sum==c}}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Thunno 2 M, 5 bytes

æDS+=

Attempt This Online!

Explanation

æDS+=  # Implicit input
æ      # Filter [1..input] by:
 D     #  Duplicate
  S    #  Sum digits
   +   #  Add
    =  #  Equals input?
       # Take the minimum
       # Implicit output
\$\endgroup\$
0
\$\begingroup\$

Haskell, 52 bytes

a n=find((==n).ap(+)(sum.map digitToInt.show))[1..n]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Scala, 71 bytes

Try it online!

n=>(0 to n).find(i=>(i.toString.map(_.asDigit).sum+i)==n).getOrElse(-1)
\$\endgroup\$

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.