| Bytes | Lang | Time | Link |
|---|---|---|---|
| 055 | C clang | 230615T171003Z | c-- |
| 155 | Rust | 240513T064211Z | 138 Aspe |
| 057 | Desmos | 230615T233507Z | Aiden Ch |
| 066 | Desmos | 240512T214556Z | fireflam |
| 071 | Scala | 230623T082244Z | 138 Aspe |
| 064 | C++ gcc | 230615T220531Z | Noodle9 |
| 052 | Haskell | 230621T040337Z | don_aman |
| 056 | Python 3 | 230620T225529Z | Kevin Ha |
| 063 | Python 3 | 230620T202131Z | Sanguine |
| 037 | Julia | 230615T175957Z | Ashlin H |
| 072 | C# .NET Core | 230615T124821Z | aloisdg |
| 005 | Thunno 2 M | 230616T170546Z | The Thon |
| 046 | Ruby | 230616T091354Z | G B |
| 044 | Wolfram Language Mathematica | 230615T084446Z | lesobrod |
| 072 | Elixir | 230615T232242Z | lbm364dl |
| 013 | Charcoal | 230615T121910Z | Neil |
| 035 | Arturo | 230615T084608Z | chunes |
| 029 | Perl 5 MListUtil=sum pa | 230615T220702Z | Xcali |
| 008 | Pyth | 230615T153025Z | CursorCo |
| 046 | R | 230615T095031Z | Dominic |
| 080 | Swift | 230615T173704Z | Bbrk24 |
| 034 | Raku | 230615T162509Z | Sean |
| 021 | APL Dyalog Extended | 230615T092538Z | Adá |
| 007 | 05AB1E | 230615T083707Z | Kevin Cr |
| 085 | Java | 230615T093236Z | Kevin Cr |
| nan | Fig | 230615T093445Z | tybocopp |
| 008 | Japt | 230615T084804Z | Shaggy |
| 049 | JavaScript | 230615T090314Z | Shaggy |
| 044 | PARI/GP | 230615T091914Z | alephalp |
| 035 | Vyxal gM | 230615T091242Z | lyxal |
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;}
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;}
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.
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! - 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
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;}
Saved 6 bytes thanks to c--!!!
Julia, 42 37 bytes
~n=argmax(x->x+sum(digits(x))==n,0:n)
-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;}
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+=
Explanation
æDS+= # Implicit input
æ # Filter [1..input] by:
D # Duplicate
S # Sum digits
+ # Add
= # Equals input?
# Take the minimum
# Implicit output
Wolfram Language (Mathematica), 89 53 49 44 bytes
#&@@Pick[r=Range@#,r+Tr/@IntegerDigits@r,#]&
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
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+]
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
Pyth, 8 bytes
x|msajdT
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}
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.
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}}
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⊥¨⍎¨∘⍕¨∘⍳
⍸ 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.
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);}
Fig, \$11\log_{256}(96)\approx\$ 9.054 bytes
[KFax'=#x+S
[ # 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
(Eventually) outputs undefined for no result.
@¶X+ìx}a
ôÈ+ì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`
Vyxal gM, 28 bitsv2, 3.5 bytes
'∑+?=
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.