g | x | w | all
Bytes Lang Time Link
055C clang230615T171003Zc--
155Rust240513T064211Z138 Aspe
057Desmos230615T233507ZAiden Ch
066Desmos240512T214556Zfireflam
071Scala230623T082244Z138 Aspe
064C++ gcc230615T220531ZNoodle9
052Haskell230621T040337Zdon_aman
056Python 3230620T225529ZKevin Ha
063Python 3230620T202131ZSanguine
037Julia230615T175957ZAshlin H
072C# .NET Core230615T124821Zaloisdg
005Thunno 2 M230616T170546ZThe Thon
046Ruby230616T091354ZG B
044Wolfram Language Mathematica230615T084446Zlesobrod
072Elixir230615T232242Zlbm364dl
013Charcoal230615T121910ZNeil
035Arturo230615T084608Zchunes
029Perl 5 MListUtil=sum pa230615T220702ZXcali
008Pyth230615T153025ZCursorCo
046R230615T095031ZDominic
080Swift230615T173704ZBbrk24
034Raku230615T162509ZSean
021APL Dyalog Extended230615T092538ZAdá
00705AB1E230615T083707ZKevin Cr
085Java230615T093236ZKevin Cr
nanFig230615T093445Ztybocopp
008Japt230615T084804ZShaggy
049JavaScript230615T090314ZShaggy
044PARI/GP230615T091914Zalephalp
035Vyxal gM230615T091242Zlyxal

C (clang), 58 55 bytes

loops forever if there's no solution

d,s;f(*i,n){for(*i=s=0;n-s|d;d=!d?s=++*i: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!

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

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

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.

Scala, 71 bytes

Try it online!

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

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

Haskell, 52 bytes

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

Try it online!

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!

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!

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

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!

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

Ruby, 46 bytes

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

Try it online!

Wolfram Language (Mathematica), 89 53 49 44 bytes

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

Try it online!

Thanks to @ovs and @att!

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!

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.

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

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

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

Try it online!

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

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.

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
}

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.

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

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)

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.

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

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

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!

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.

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.