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.

• If there is no solution, is it acceptable to loop forever without output, or do we need to terminate?
– xnor
Commented Jun 15, 2023 at 8:31
• @xnor That's okay. Commented Jun 15, 2023 at 8:41
• Presumably the expected output for 0 is 0? Commented Jun 15, 2023 at 14:09
• @Shaggy Yes. 0 + (0) is indeed 0 Commented Jun 15, 2023 at 16:12
• 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. Commented Jun 15, 2023 at 22:31

# VyxalgM, 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.
• Lol, I've been ninja'd Commented Jun 15, 2023 at 9:14

# 05AB1E, 7 bytes

Ý.ΔDªOQ

Outputs -1 if there is no result.

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)
• That was quick! Commented Jun 15, 2023 at 8:40
• @TomEpsilon Could have been quicker if I saw the challenge 10 minutes earlier. ;) Nice first challenge btw, and welcome to CGCC! Commented Jun 15, 2023 at 8:41

# 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.

# 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
ì         :  Convert to digit array
Ã       :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
ì        :      Convert X to digit array
}      :End function
a     :Get the first integer >=0 that returns true
• Yup, your second version is what I came up with as well. (This is Jacob, I changed my username) Commented Jun 15, 2023 at 12:22
• 6 bytes +ìx ¥N Commented Jun 15, 2023 at 12:43
• 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? Commented Jun 15, 2023 at 13:44
• Scratch that, @noodleman; it fails for 0. Commented Jun 15, 2023 at 14:08
• 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. Commented Jun 15, 2023 at 15:37

# 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

• I’m sorry, but what does “ lit. cum. right-ass. less red.” mean? Commented Jun 15, 2023 at 11:25
• @TomEpsilon literally cumulative right-associative less reduction
Commented Jun 15, 2023 at 12:02

# 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!

# 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--!!!

• @c-- Nice one - thanks! :D Commented Jun 16, 2023 at 10:06
• @c-- Very good - thanks! :D Commented Jun 22, 2023 at 20:40

# 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!

# 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.

# 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.

• You have an extra space at the start of you code... Commented Jun 15, 2023 at 17:57
• @pajonk - Ah, thanks v much for spotting that! Commented Jun 15, 2023 at 18:16

# Pyth, 8 bytes

x|msajdT

Try it online!

Returns -1 for no result.

### Explanation

# 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

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

# 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

# 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!

# Wolfram Language (Mathematica), 895349 44 bytes

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

Try it online!

Thanks to @ovs and @att!

• That was hell of an optimization. Commented Jun 15, 2023 at 8:56
• Sure it can be more golfed Commented Jun 15, 2023 at 8:58
• 49 bytes with Range[n=#] and Tr instead of Total.
– ovs
Commented Jun 15, 2023 at 9:54
• 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
– att
Commented Jun 16, 2023 at 1:00

# 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

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

# 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.

# Charcoal, 13 bytes

ＮθＩ⌊Φ⊕θ⁼θ⁺ιΣι

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.

Ｎθ              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
Ｉ             Cast to string
Implicitly print

23 bytes for a less inefficient version:

ＮθＩ⌊Φ…·⁻θ×⁹Ｌθθ⁼θ⁺ιΣ⌈⟦⁰ι

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:

ＮθＩ⌊ΦＥＬθ⁻⁻θ﹪×⁵θ⁹×⁹ι⁼θ⁺ιΣ⌈⟦⁰ι

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.

# 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!

• You can remove the space at return-1; like in my Java answer for -1 byte. :) Commented Jun 16, 2023 at 8:45
• @KevinCruijssen forgot this one. Thank you! Commented Jun 16, 2023 at 17:05

# 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!

• Welcome to Code Golf, and nice first answer! Commented Jun 20, 2023 at 21:15

# 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!

• Welcome to Code Golf, and nice answer! Commented Jun 20, 2023 at 23:23
• o*(...)or f(... saves a byte. Commented Jul 17, 2023 at 15:24

# 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).

# 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
)
}

Try it online!

# Ruby, 46 bytes

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

Try it online!

# Thunno 2M, 5 bytes

æDS+=

Attempt This Online!

#### Explanation

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

# Desmos, 66 bytes

d(n)=mod(n,10)+d(floor(n/10))
d(0)=0
I=[0...n]
f(n)=I[n=I+d(I)][1]

Returns undefined (NaN) if no solution exists.

Try It On Desmos!

Try It On Desmos! - Prettified

Note that the recursive function d(n) for digital sum does not terminate for n<0. Desmos automatically tries to plot the expression, which freezes the web worker. It'll eventually un-freeze due to the 10000 depth limit, so this is still a valid solution, but if you want to paste this in practice, modify d(n) so it terminates, then disable plotting for d and f, then undo the modification to d.

Summation seems strictly better than recursion when summation can do the job because recursion has many bytes of overhead: need to write d()= twice and d() at least once, if using external base cases. Need to write d()= once and d() at least once, plus \{:,\} if using piecewise-defined base cases.

# Desmos, 66 57 bytes

-9 bytes thanks to @fireflame241!!!

I=[0...n]
f(n)=I[I+∑_{k=0}^Imod(floor(I/10^k),10)=n][1]

Returns undefined if no solution exists.

Try It On Desmos!

Try It On Desmos! - Prettified

• -1 byte by using [1] instead of .min Commented May 12 at 21:34
• -many bytes by using broadcasting instead of listcomp: desmos.com/calculator/udf3s2xku5 Commented May 12 at 21:52

# Rust, 155 bytes

Golfed version. Attempt This Online!

|n:i32|->i32{(0..=n).map(|i|{let d:i32=i.to_string().chars().map(|c|c.to_digit(16).unwrap()as i32).sum();(i,d+i)}).find(|&(_,s)|s==n).unwrap_or((-1,-1)).0}

Ungolfed version. Attempt This Online!

fn f(n: i32) -> i32 {
(0..=n).map(|i| {
let digit_sum: i32 = i.to_string()
.chars()
.map(|c| c.to_digit(16).unwrap() as i32)
.sum();
(i, digit_sum + i)
})
.find(|&(_, sum)| sum == n)
.unwrap_or((-1, -1)) // If no match is found, return (-1, -1)
.0
}

fn main() {
let expected = [0, -1, 1, -1, 2, -1, 3, -1, 4, -1, 5, 10, 6, 11, 7, 12, 8, 13, 9, 14, -1, 15, 20, 16, 21, 17, 22, 18, 23, 19, 24, -1, 25, 30, 26, 31, 27, 32, 28, 33, 29, 34, -1, 35, 40, 36, 41, 37, 42, 38, 43, 39, 44, -1, 45, 50, 46, 51, 47, 52, 48, 53, 49, 54, -1, 55, 60, 56, 61, 57, 62];

for (index, &e) in expected.iter().enumerate() {
if e == -1 { continue; } // Skip testing cases with expected result -1

let result = f(index as i32);
let correct = result == e;
let status = if correct { "✓" } else { "✗" };

println!("{:02} -> {} {}", index, result, status);
}
}