# Question
Title: Convert a decimal integer to binary only using arithmetic operators
There are 10 types of people in the world, those who understand binary and those who do not.

Where are you? Let's see!

# Challenge

Your task is to convert a decimal integer to binary, only using a set of arithmetic operators (+, -, \*, / and %). You can use conditional statements, loops and variables. (No bitwise operator/No Builtin methods or function).

# Input

A decimal integer.

# Output

The binary number.

# Examples

```
2 -> 10
6 -> 110
etc...

```

The shortest code wins.

# Answer
> 9 votes
# Python 2, 30 bytes

```
f=lambda n:n and n%2+10*f(n/2)

```

Try it online!

# Answer
> 6 votes
# JavaScript (Node.js), 28 bytes

```
f=x=>x?x%2+10*f((x-x%2)/2):x

```

Try it online!

# Answer
> 5 votes
# C (gcc), <sup>~~50~~ ~~27~~</sup> 26 bytes

```
f(n){n=n?n%2+10*f(n/2):n;}

```

Try it online!

# Answer
> 5 votes
# Whitespace, 141 bytes

```
[S S S T    N
_Push_1][S N
S _Dupe_1][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Dupe_input][N
S S N
_Create_Label_LOOP][S N
S _Dupe_top][N
T   S S N
_If_0_Jump_to_Label_LOOP2][S S S T  N
_Push_1][T  S S T   _Subtract][S N
T   _Swap_top_two][S N
S _Dupe_top][S S S T    S N
_Push_2][T  S T T   _Modulo][S N
T   _Swap_top_two][S S S T  S N
_Push_2][T  S T S _Integer_divide][S T  S S T   S N
_Copy_0-based_2nd][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_LOOP2][S N
T   _swap_top_two][S S S T  N
_Push_1][S N
S _Dupe_1][T    T   T   _Retrieve_input][T  S S T   _Subtract][T    S S S _Add][N
T   S T N
_If_0_Jump_to_Label_DONE][S S S T   S T S N
_Push_10][T S S N
_Multiply][T    S S S _Add][N
S N
S N
_Jump_to_Label_LOOP2][N
S S T   N
_Create_Label_DONE][T   N
S T _Print_as_integer_to_STDOUT]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Funny thing is, is that I can use everything Whitespace has to offer for this challenge. So even if builtins were allowed, this would still be the approach to use, since Whitespace has none. ;)

**Explanation in pseudo-code:**

```
Integer input = read STDIN as integer
Integer index = input
Integer b = input
Start LOOP:
  If(index == 0):
    Jump to LOOP2
  index = index - 1
  Integer a[index] = b[previous_index] modulo-2
  Integer b[index] = b[previous_index] integer-divided by 2
  Go to next iteration of LOOP

Start LOOP2:
  If(index+1 == input):
    Jump to DONE
  a = a + b*10
  Go to next iteration of LOOP2

Label DONE:
  Print a as integer to STDOUT
  (stop program implicitly with an error)

```

**Example run: `input = 6`**

```
Command  Explanation                 Stack                             Heap  STDIN STDOUT

SSST     Push 1                      [1]
SNS      Duplicate top (1)           [1,1]
TNTT     Read STDIN as integer       [1]                               {1:6} 6
TTT      Retrieve input from heap    [6]                               {1:6}
SNS      Duplicate top (6)           [6,6]                             {1:6}
NSSN     Create Label LOOP           [6,6]                             {1:6}
 SNS      Duplicate top (6)          [6,6,6]                           {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [6,6]                             {1:6}
 SSSTN    Push 1                     [6,6,1]                           {1:6}
 TSST     Subtract (6-1)             [6,5]                             {1:6}
 SNT      Swap top two               [5,6]                             {1:6}
 SNS      Duplicate top (6)          [5,6,6]                           {1:6}
 SSSTSN   Push 2                     [5,6,6,2]                         {1:6}
 TSTT     Modulo (6%2)               [5,6,0]                           {1:6}
 SNT      Swap top two               [5,0,6]                           {1:6}
 SSSTSN   Push 2                     [5,0,6,2]                         {1:6}
 TSTS     Integer-divide (6//2)      [5,0,3]                           {1:6}
 STSSTSN  Copy 0-based 2nd (5)       [5,0,3,5]                         {1:6}
 NSNN     Jump to Label LOOP         [5,0,3,5]                         {1:6}

 SNS      Duplicate top (5)          [5,0,3,5,5]                       {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,3,5]                         {1:6}
 SSSTN    Push 1                     [5,0,3,5,1]                       {1:6}
 TSST     Subtract (5-1)             [5,0,3,4]                         {1:6}
 SNT      Swap top two               [5,0,4,3]                         {1:6}
 SNS      Duplicate top (3)          [5,0,4,3,3]                       {1:6}
 SSSTSN   Push 2                     [5,0,4,3,3,2]                     {1:6}
 TSTT     Modulo (3%2)               [5,0,4,3,1]                       {1:6}
 SNT      Swap top two               [5,0,4,1,3]                       {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,2]                     {1:6}
 TSTS     Integer-divide (3//2)      [5,0,4,1,1]                       {1:6}
 STSSTSN  Copy 0-based 2nd (4)       [5,0,4,1,1,4]                     {1:6}
 NSNN     Jump to Label LOOP         [5,0,4,1,1,4]                     {1:6}

 SNS      Duplicate top (4)          [5,0,4,1,1,4,4]                   {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,4,1,1,4]                     {1:6}
 SSSTN    Push 1                     [5,0,4,1,1,4,1]                   {1:6}
 TSST     Subtract (4-1)             [5,0,4,1,1,3]                     {1:6}
 SNT      Swap top two               [5,0,4,1,3,1]                     {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,3,1,1]                   {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,1,2]                 {1:6}
 TSTT     Modulo (3%2)               [5,0,4,1,3,1,1]                   {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,1]                   {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,1,2]                 {1:6}
 TSTS     Integer-divide (1//2)      [5,0,4,1,3,1,0]                   {1:6}
 STSSTSN  Copy 0-based 2nd (3)       [5,0,4,1,3,1,0,3]                 {1:6}
 NSNN     Jump to Label LOOP         [5,0,4,1,3,1,0,3]                 {1:6}

 SNS      Duplicate top (3)          [5,0,4,1,3,1,0,3,3]               {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,4,1,3,1,0,3]                 {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,0,3,1]               {1:6}
 TSST     Subtract (3-1)             [5,0,4,1,3,1,0,2]                 {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0]                 {1:6}
 SNS      Duplicate top (0)          [5,0,4,1,3,1,2,0,0]               {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,0,2]             {1:6}
 TSTT     Modulo (0%2)               [5,0,4,1,3,1,2,0,0]               {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,0]               {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,0,2]             {1:6}
 TSTS     Integer-divide (0//2)      [5,0,4,1,3,1,2,0,0]               {1:6}
 STSSTSN  Copy 0-based 2nd (2)       [5,0,4,1,3,1,2,0,0,2]             {1:6}
 NSNN     Jump to Label LOOP         [5,0,4,1,3,1,2,0,0,2]             {1:6}

 SNS      Duplicate top (2)          [5,0,4,1,3,1,2,0,0,2,2]           {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,4,1,3,1,2,0,0,2]             {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,2,0,0,2,1]           {1:6}
 TSST     Subtract (2-1)             [5,0,4,1,3,1,2,0,0,1]             {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0]             {1:6}
 SNS      Duplicate top (0)          [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,1,0,0,2]         {1:6}
 TSTT     Modulo (0%2)               [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,1,0,0,2]         {1:6}
 TSTS     Integer-divide (0//2)      [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 STSSTSN  Copy 0-based 2nd (1)       [5,0,4,1,3,1,2,0,1,0,0,1]         {1:6}
 NSNN     Jump to Label LOOP         [5,0,4,1,3,1,2,0,1,0,0,1]         {1:6}

 SNS      Duplicate top (1)          [5,0,4,1,3,1,2,0,1,0,0,1,1]       {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,4,1,3,1,2,0,1,0,0,1]         {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,2,0,1,0,0,1,1]       {1:6}
 TSST     Subtract (1-1)             [5,0,4,1,3,1,2,0,1,0,0,0]         {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0,0,0]         {1:6}
 SNS      Duplicate top (0)          [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,1,0,0,0,0,2]     {1:6}
 TSTT     Modulo (0%2)               [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 SSSTSN   Push 2                     [5,0,4,1,3,1,2,0,1,0,0,0,0,2]     {1:6}
 TSTS     Integer-divide (0//2)      [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 STSSTSN  Copy 0-based 2nd (0)       [5,0,4,1,3,1,2,0,1,0,0,0,0,0]     {1:6}
 NSNN     Jump to Label LOOP         [5,0,4,1,3,1,2,0,1,0,0,0,0,0]     {1:6}

 SNS      Duplicate top (1)          [5,0,4,1,3,1,2,0,1,0,0,0,0,0,0]   {1:6}
 NTSSN    If 0: Jump to Label LOOP2  [5,0,4,1,3,1,2,0,1,0,0,0,0,0]     {1:6}
NSSSN    Create Label LOOP2          [5,0,4,1,3,1,2,0,1,0,0,0,0,0]     {1:6}
 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0,0,0,0,0]     {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1]   {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1,1] {1:6}
 TTT      Retrieve input from heap   [5,0,4,1,3,1,2,0,1,0,0,0,0,0,1,6] {1:6}
 TSST     Subtract (1-6)             [5,0,4,1,3,1,2,0,1,0,0,0,0,0,-5]  {1:6}
 TSSS     Add (0+-5)                 [5,0,4,1,3,1,2,0,1,0,0,0,0,-5]    {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 SSSTSTSN Push 10                    [5,0,4,1,3,1,2,0,1,0,0,0,0,10]    {1:6}
 TSSN     Multiply (0*10)            [5,0,4,1,3,1,2,0,1,0,0,0,0]       {1:6}
 TSSS     Add (0+0)                  [5,0,4,1,3,1,2,0,1,0,0,0]         {1:6}
 NSNSN    Jump to Label LOOP2        [5,0,4,1,3,1,2,0,1,0,0,0]         {1:6}

 SNT      Swap top two               [5,0,4,1,3,1,2,0,1,0,0,0]         {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,2,0,1,0,0,0,1]       {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,3,1,2,0,1,0,0,0,1,1]     {1:6}
 TTT      Retrieve input from heap   [5,0,4,1,3,1,2,0,1,0,0,0,1,6]     {1:6}
 TSST     Subtract (1-6)             [5,0,4,1,3,1,2,0,1,0,0,0,-5]      {1:6}
 TSSS     Add (0+-5)                 [5,0,4,1,3,1,2,0,1,0,0,-5]        {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 SSSTSTSN Push 10                    [5,0,4,1,3,1,2,0,1,0,0,10]        {1:6}
 TSSN     Multiply (0*10)            [5,0,4,1,3,1,2,0,1,0,0]           {1:6}
 TSSS     Add (0+0)                  [5,0,4,1,3,1,2,0,1,0]             {1:6}
 NSNSN    Jump to Label LOOP2        [5,0,4,1,3,1,2,0,1,0]             {1:6}

 SNT      Swap top two               [5,0,4,1,3,1,2,0,0,1]             {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,2,0,0,1,1]           {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,3,1,2,0,0,1,1,1]         {1:6}
 TTT      Retrieve input from heap   [5,0,4,1,3,1,2,0,0,1,1,6]         {1:6}
 TSST     Subtract (1-6)             [5,0,4,1,3,1,2,0,0,1,-5]          {1:6}
 TSSS     Add (1+-5)                 [5,0,4,1,3,1,2,0,0,-4]            {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,4,1,3,1,2,0,0]               {1:6}
 SSSTSTSN Push 10                    [5,0,4,1,3,1,2,0,0,10]            {1:6}
 TSSN     Multiply (0*10)            [5,0,4,1,3,1,2,0,0]               {1:6}
 TSSS     Add (0+0)                  [5,0,4,1,3,1,2,0]                 {1:6}
 NSNSN    Jump to Label LOOP2        [5,0,4,1,3,1,2,0]                 {1:6}

 SNT      Swap top two               [5,0,4,1,3,1,0,2]                 {1:6}
 SSSTN    Push 1                     [5,0,4,1,3,1,0,2,1]               {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,3,1,0,2,1,1]             {1:6}
 TTT      Retrieve input from heap   [5,0,4,1,3,1,0,2,1,6]             {1:6}
 TSST     Subtract (1-6)             [5,0,4,1,3,1,0,2,-5]              {1:6}
 TSSS     Add (2+-5)                 [5,0,4,1,3,1,0,-3]                {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,4,1,3,1,0]                   {1:6}
 SSSTSTSN Push 10                    [5,0,4,1,3,1,0,10]                {1:6}
 TSSN     Multiply (0*10)            [5,0,4,1,3,1,0]                   {1:6}
 TSSS     Add (1+0)                  [5,0,4,1,3,1]                     {1:6}
 NSNSN    Jump to Label LOOP2        [5,0,4,1,3,1]                     {1:6}

 SNT      Swap top two               [5,0,4,1,1,3]                     {1:6}
 SSSTN    Push 1                     [5,0,4,1,1,3,1]                   {1:6}
 SNS      Duplicate top (1)          [5,0,4,1,1,3,1,1]                 {1:6}
 TTT      Retrieve input from heap   [5,0,4,1,1,3,1,6]                 {1:6}
 TSST     Subtract (1-6)             [5,0,4,1,1,3,-5]                  {1:6}
 TSSS     Add (3+-5)                 [5,0,4,1,1,-2]                    {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,4,1,1]                       {1:6}
 SSSTSTSN Push 10                    [5,0,4,1,1,10]                    {1:6}
 TSSN     Multiply (1*10)            [5,0,4,1,10]                      {1:6}
 TSSS     Add (1+10)                 [5,0,4,11]                        {1:6}
 NSNSN    Jump to Label LOOP2        [5,0,4,11]                        {1:6}

 SNT      Swap top two               [5,0,11,4]                        {1:6}
 SSSTN    Push 1                     [5,0,11,4,1]                      {1:6}
 SNS      Duplicate top (1)          [5,0,11,4,1,1]                    {1:6}
 TTT      Retrieve input from heap   [5,0,11,4,1,6]                    {1:6}
 TSST     Subtract (1-6)             [5,0,11,4,-5]                     {1:6}
 TSSS     Add (4+-5)                 [5,0,11,-1]                       {1:6}
 NTSTN    If 0: Jump to Label DONE   [5,0,11]                          {1:6}
 SSSTSTSN Push 10                    [5,0,11,10]                       {1:6}
 TSSN     Multiply (11*10)           [5,0,110]                         {1:6}
 TSSS     Add (1+10)                 [5,110]                           {1:6}
 NSNSN    Jump to Label LOOP2        [5,110]                           {1:6}

 SNT      Swap top two               [110,5]                           {1:6}
 SSSTN    Push 1                     [110,5,1]                         {1:6}
 SNS      Duplicate top (1)          [110,5,1,1]                       {1:6}
 TTT      Retrieve input from heap   [110,5,1,6]                       {1:6}
 TSST     Subtract (1-6)             [110,5,-5]                        {1:6}
 TSSS     Add (5+-5)                 [110,0]                           {1:6}
 NTSTN    If 0: Jump to Label DONE   [110]                             {1:6}
NSSTN    Create Label DONE           [110]                             {1:6}
 TNST     Print as integer to STDOUT []                                {1:6}      110

```

Stops with an error after printing the result, because no exit is defined.

# Answer
> 4 votes
# 05AB1E, 11 bytes

```
F2‰`s}ÎƒT*+

```

Fixed with help of *@Grimmy*.

Try it online or verify the first \\$\[0,25\]\\$ inputs.

**Explanation:**

```
F       # Loop the (implicit) input-integer amount of times:
 2‰     #  Take the divmod-2 ([n//2, n%2]) of the top value on the stack
        #  (which will be the (implicit) input-integer in the very first iteration)
   `s   #  Push them separated to the stack, and swap their order
}Î      # After the loop: push 0 and the input to the stack
  ƒ     #  Loop the input+1 amount of times:
   T*   #  Multiply the top value by 10
     +  #  And add the top two values together
        # (after which it is output implicitly as result)

```

# Answer
> 4 votes
# PHP, ~~45~~ ~~44~~ 43 bytes

```
for(;$a=&$argn>=1;$a/=2)$n=$a%2 .$n;echo$n;

```

Try it online!

As the output is a string, it supports up to `PHP_INT_MAX` integers

Thanks to @MariaMiller for saving 1 byte!

Thanks to @GuillermoPhillips for the reference assignment trick!

# Answer
> 4 votes
# Perl 5 `-Minteger -p`, 32 bytes

```
$\+=$_%2*10**$i++,$_/=2while$_}{

```

Try it online!

Uses no concatenation. If concatenation is allowed, it would get a little shorter:

### 26 bytes

```
$\=$_%2 .$\,$_/=2while$_}{

```

Try it online!

# Answer
> 4 votes
# Ruby, 26 bytes

```
f=->n{n>0?n%2+10*f[n/2]:n}

```

Try it online!

# Answer
> 3 votes
# Erlang (escript), 36 bytes

Port of various answers.

```
b(0)->0;b(N)->N rem 2+10*b(N div 2).

```

Try it online!

# Erlang (escript), 37 bytes

Outputs a list of integers; it's longer by 1 byte anyway with concatenation ...

```
b(0)->[];b(N)->b(N div 2)++[N rem 2].

```

Try it online!

# Answer
> 3 votes
# MathGolf, 12 bytes

Longer than 05AB1E because MathGolf doesn't have divmod ...

```
_{2‼%/}k{♂*+

```

Try it online!

# Explanation

```
_            We have to copy the input because
             MathGolf outputs 0 over an empty stack.
 {    }      Do that input times:
   ‼%/       "Moddiv"
  2          by 2 (This saves the swapping of the stack)
       k     Repeat input times:
        {♂*  Multiply TOS by 10
           + And add second-to-top

```

# MathGolf, 10 bytes

If only concatenation is allowed. MathGolf cleverly avoids the leading zeroes, unlike 05AB1E which doesn't.

```
_{2‼%/}]yx

```

Try it online!

# Explanation

```
_          We have to copy the input because
           MathGolf outputs 0 over an empty stack.
 {2‼%/}    Mod-div by 2 input times over input
       ]   Wrap whole stack into a list
        y  Join the list into a number
         x Reverse the number, removing leading zeroes
           Anyway, the old 05AB1E answer used it, so I guess it's valid...

```

# Answer
> 3 votes
# PHP, 55 bytes

```
for($p=2**32;$p=$p/2%$p;)echo($f+=$v=$argn/$p%2)?$v:'';

```

Try it online!

If concatenation is allowed, then see the other PHP answer by @Kaddath.

**How**

Take digits starting from most significant bit, which is leftmost. To strip leading zeroes, just accumulate the bit values until it goes above 0, then start displaying.

Doesn't work for zero! Not sure if I'm allowed to have the power (\**) operator?

# Answer
> 2 votes
# brainfuck, 50 bytes

```
>,[[->>>+<[-<+>>-]>[-<+>>]<<<<]+>>[-<<+>>]<]<[-.<]

```

Try it online! (with 10 as input)... Or try this naïve version with human-readable output, where I just added 48 + signs by hand, so that you guys can read the output.

How it works:

Reads the input and does the following, iteratively:

* divide by 2, finding quotient and remainder
* save the remainder + 1 on the left (this will make it easier to retrace the binary representation later)
* move the tape right and repeat with this quotient as the new input

Then we walk left, printing the remainders, by first decreasing them by 1 to restore their real value.

# Answer
> 2 votes
# Jelly, 8 bytes

```
HḞÐ¿ṖḂṚḞ

```

Try it online!

A monadic link taking an integer and returning a list of binary digits.

## Explanation

```
 ḞÐ¿     | While the current value converted to integer (by flooring) is non-zero, do the following, collecting up intermediate values:
H        | - Halve
    Ṗ    | Remove last
     Ḃ   | Mod 2
      Ṛ  | Reverse list
       Ḟ | Convert to integer

```

# Answer
> 2 votes
# Perl 6, 26 bytes

```
{[R~] ($_,*div 2...^0)X%2}

```

Try it online!

Uses concatenation, as well as some questionable interpretations of `loop`s for `[R~]`, `...` and `X`.

# Answer
> 2 votes
# Japt, 9 bytes

```
©u +A*ßUz

```

Try it

# Answer
> 1 votes
# K (ngn/k), 26 bytes

```
1_(*:){(-2 2!\:*x),1_x}/,:

```

Try it online!

# Answer
> 0 votes
## Pascal, 160 B

This is a complete `program` according to ISO standard 7185 “Standard Pascal” using your standard Horner scheme recursively.

```
program p(input,output);var n:integer;procedure p(n:integer);begin if n>1 then p(n div 2);write(n mod 2:1)end;begin read(n);if n<0 then write('-');p(abs(n))end.

```

Ungolfed:

```
program changeBaseDecimalToBinary(input, output);

var
    n: integer;

procedure convert(n: integer);
begin
    if n > 1 then
    begin
        convert(n div 2)
    end;
    { Print in reverse order. ----------------------------------- }

    { The `:1` specifies the _minimum_ width.
      If omitted, a processor-defined default is inserted.
      This would potentially cause ugly spaces between digits. }
    write(n mod 2:1)
end;

{ === MAIN ====================================================== }
begin
    read(n);
    { In Extended Pascal you would write `write('−':ord(n < 0))`. }
    if n < 0 then
    begin
        write('−')
    end;

    convert(abs(n))
end.

```

---
Tags: code-golf, math, binary, conversion
---


title: Encrypt AES256 (ECB Cipher Mode)

text:
# Question
Title: Encrypt AES256 (ECB Cipher Mode)
I've looked and could not find a post for this, if there is one, I'll remove it quick! Related and also related

The goal is (hopefully) clear: create the shortest code (in bytes) that implements the AES256 ECB cipher mode. Either convert the result to Base64 or output a array of bytes. The input contains two parts. The first part is the stuff to encrypt, and the second part (separated by newlines) is the secret key. You do not need to decrypt it!

## Test cases!

**Input:**

```
AES Encryption!
averygoodsecretpasswordthatsgood

```

**Output:**

```
VBWQy7umRdabP1xs2y1Oqg==

```

You may output as an array of bytes too, if you wish.

# Answer
# JavaScript (Node.js), 90 bytes

*Disclaimer: even with clean ungolfed code, don't use ECB mode for anything serious unless you're 100% certain its weaknesses are acceptable for your use case.*

Expects `(string)(key)` and returns an array of bytes.

```
s=>k=>[...(c=require('crypto').createCipheriv("aes-256-ecb",k,"")).update(s),...c.final()]

```

Try it online!
> 5 votes

---
Tags: code-golf, cryptography
---


# Question
Title: Find the average, median, mode, and range
It's easier to put this into coding terminology, so here we go:

1. First find the average, median, mode, and range.
2. Then, put those values in another array, then find the new average, median, mode, and range.
3. Bonus -10 bytes (yeah, negative bytes, because there's already answers) for programs that can handle this many times (repeat the first steps N times with an extra parameter)
4. Then average those numbers. If there are multiple medians or modes, simply average them!

## Test cases:

```
[1, 2, 3, 4, 5] -> 2.5625
[1, 1, 1, 1, 1] -> 0.9375
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] -> 48.5
[0, 5, 10, 50] -> 24.375
[4, 4, 8, 10, 16, 24, 100, 150, 200, 200, 250] -> 136.7045454545454545454545454545... (it's fine if there's floating-point inaccuracies)

```

As this is , the shortest code in bytes wins!

# Answer
> 4 votes
# Vyxal, 28 - 10 = 18 bytes

```
(λṁn∆ṁwfṁnDvOÞMİṁn₌Gg-WW;†)ṁ

```

Try it Online!

A horrible mess of `n`s, s and other letters.

## Explained

```
(λṁn∆ṁwfṁnDvOÞMİṁn₌Gg-WW;†)ṁ
(                         )  # first inputh times
 λ                      ;†   # do to argument n:
  ṁ                          #  mean of n
   n∆ṁwfṁ                    #  average of medians of n
         nDvOÞMİṁ            #  average of modes of n. If it was smallest mode or first mode, this could just be ∆M
                 ₌Gg-        #  range of n
                     WW      #  wrap into a list
                           ṁ # average of that

```

# Answer
> 3 votes
# 05AB1E, score: 14 (24 bytes \- 10 bonus)

```
ƒD©Åm®Ð¢ZQÏ®Zsß-)ε¸˜ÅA]н

```

First input is \\$n\\$, second is the list.

Try it online or verify all test cases.

**Explanation:**

```
ƒ        # Loop the first (implicit) input + 1 amount of times:
 D       #  Duplicate the current list
         #  (which will be the second implicit input-list in the first iteration)
 ©       #  Store it in variable `®` (without popping)
  Åm     #  Pop and get its mean
 ®       #  Push list `®` again
  Ð      #  Triplicate it
   ¢     #  Pop both copies, and get the count of each value
    Z    #  Push the maximum (without popping the list of counts)
     Q   #  Check which counts are equal to this maximum
      Ï  #  Only keep the values at those truthy values
 ®       #  Push list `®` yet again
  Z      #  Push its maximum (without popping the list)
   s     #  Swap so the list is at the top of the stack
    ß    #  Pop and push its minimum
     -   #  Subtract the minimum from the maximum
 )       #  Wrap all four items on the stack into a list
  ε      #  Map over this quadruplet:
   ¸     #   Wrap it in a list (for the fourth item; and optionally the mean)
    ˜    #   Flatten it (in case it was already a list)
     ÅA  #   Get the average of this
]        # Close both the map and loop
 н       # Pop and push the first item (the average of the extra iteration)
         # (after which the result is output implicitly)

```

---
Tags: code-golf
---


title: Is it a balanced number?

text:
# Question
Title: Is it a balanced number?
A number is balanced if the sum of the digits on each half of the number is equal, so: `1423` is balanced because `1+4 = 2+3`, so is: `42615` because `4+2=1+5`. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

**Challenge:**

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

**Test cases (true)**

```
1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088

```

**Test cases (false)**

```
10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454

```

There will not be numbers starting with zero, for instance `00032` instead of `32`. You must support numbers up to at least 100 digits (so larger than `2^64-1`). As always, optional input format, so you may surround the number with apostrophes if desired.

# Answer
# 05AB1E, ~~14~~ 7 bytes

```
€D2äO`Q

```

**Explanation**

Using **141** as example:

```
€D       # duplicate each (turns the number into a list of digits)
         # STACK: ['1','1','4','4','1','1']
  2ä     # split list in 2 (as we duplicated each element,
         # the middle element will exist on both sides for an odd length input
         # STACK: [['1','1','4'],['4','1','1']]
    O    # sum each sublist
         # STACK: [6,6]
     `   # flatten
         # STACK: 6, 6
      Q  # compare for equality
         # STACK: 1 (true)

```

Try it online!
> 12 votes

# Answer
# \>\<\>, ~~31~~ 29 bytes

```
i:0(?v
~00}v>
v+r+>l4(?
>{=n;

```

Try it online!

Line 1: Standard input loop

Line 2: Discard the -1 on top of the stack, push two 0's and rotate one to the bottom of the stack (this ensures that inputs of length \<3 don't exhaust the stack later in the program)

Line 3: If the length of the stack is \>3, add the top two and bottom two elements of the stack together.

Line 4: If top and bottom of the stack are equal, output 1, 0 otherwise.

*Edit: realised that there's no need to take the characters mod 12, 2 bytes saved*
> 10 votes

# Answer
# Haskell, ~~64~~ 63 bytes

```
b(a:t@(r:s))=a-last t+b(init t);b _=0
(==0).b.map fromEnum.show

```

One Byte Saved thanks to nimi
> 7 votes

# Answer
# Brachylog, 20 bytes

```
@eL@2tM,Lr@2t:M:+a#=

```

Try it online!

### Explanation

```
@eL                    Get the list of digits L of the input
  L@2tM,               Get the second half M of L
        Lr@2t          Get the second half of the reverse of L
             :M        The list [L, M]
               :+a#=   The sum of elements of L and the sum of elements of M must be equal

```
> 6 votes

# Answer
## Mathematica, 57 bytes

```
Tr@(#-Reverse@#)[[;;⌊Length@#/2⌋]]==0&@*IntegerDigits

```

### Explanation

I was really hoping I could use this approach in some language, and it seems to be doing fairly well in Mathematica. The idea is to avoid having to obtain both the front and the back half by combining the list with its reverse and looking *only* at the front half.

```
...&@*IntegerDigits

```

First, we turn the input into a list of decimal digits and pass the result to the unnamed function on the left.

```
...(#-Reverse@#)...

```

Now we subtract the reverse of the list from the list itself. If the digits are `{a<sub>1</sub>,a<sub>2</sub>,...,a<sub>n</sub>}` then the result will be `{a<sub>1</sub>-a<sub>n</sub>,a<sub>2</sub>-a<sub>n-1</sub>,...,a<sub>n</sub>-a<sub>1</sub>}`.

```
...[[;;⌊Length@#/2⌋]]

```

We extract the first half of this list (excluding the middle digit although that doesn't actually matter, because the corresponding difference will be `0` anyway).

```
Tr@...

```

And then we sum this list. So that's:

```
a<sub>1</sub> - a<sub>n</sub> + a<sub>2</sub> - a<sub>n-1</sub> + ... + a<sub>⌊n/2⌋</sub> - a<sub>⌈n/2⌉+1</sub>
```

Rearranging:

```
a<sub>1</sub> + a<sub>2</sub> + ... + a<sub>⌊n/2⌋</sub> - (a<sub>⌈n/2⌉+1</sub> + ... + a<sub>n-1</sub> + a<sub>n</sub>)
```

The input is balanced if the two halves have the same sum. Hence, this expression is zero if the input is balanced. So that's what we check:

```
...==0

```
> 6 votes

# Answer
# Java, 85 bytes

```
n->{int s=0,i=0,l=n.length();for(;i<l/2;)s+=n.charAt(i)-n.charAt(l-++i);return s==0;}

```

Note: the input is given as `String` as Java can't handle without `BigInteger` (and `BigInteger`s are constructed using a... `String`.)

## Testing and ungolfed:

```
import java.util.function.Predicate;

public class Main {

  public static void main(String[] args) {
    Predicate<String> f = n -> {
      int s = 0, i = 0, l = n.length();
      for (; i < l / 2;) {
        s += n.charAt(i) - n.charAt(l - ++i);
      }
      return s == 0;
    };

    String[] truthies = {"1",
      "6",
      "11",
      "141",
      "23281453796004414",
      "523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"};
    for (String s : truthies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
    String[] falsies = {"10",
      "12",
      "110",
      "15421",
      "5234095123508321",
      "6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"};
    for (String s : falsies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
  }
}

```
> 5 votes

# Answer
# JavaScript (ES6), ~~59~~ ~~55~~ ~~51~~ ~~44~~ 42 bytes

```
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n

```

Turns out I was using the wrong strategy entirely. This version recursively finds the sum of the first half minus the sum of the second half, then returns the logical NOT of the result.

If we could return falsy in place of truthy and vice-versa, this would be 35 bytes:

```
f=([x,...a])=>a[0]?x-a.pop()+f(a):0

```

### Test snippet

```
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n
```

```
<input id=I value="23281453796004414"><br>
<button onclick="console.log(`Result of f(${I.value}): `+f(I.value))">Run</button>
```
> 5 votes

# Answer
## Haskell, 55 bytes

```
g(h:t)=read[h]-g(reverse t)
g _=0
(==0).g.(<*"xx").show

```

The recursive function `g` unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half.

```
   g "12345"
== 1 - g "5432"
== 1 - (5 - g "432")
== 1 - (5 - (4 - g "32"))
== 1 - (5 - (4 - (3 - g "2"))
== 1 - (5 - (4 - (3 - 2))
== 1 + 2 + 3 - 4 - 5

```

So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by `(<*"xx")`, which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out.
> 5 votes

# Answer
## Python 3, ~~107~~ ~~102~~ 76 bytes

```
n=input()
l=len(n)
print(sum(map(int,n[:l//2]))==sum(map(int,n[l//2+l%2:])))

```

-26 bytes by @Rod!
> 4 votes

# Answer
## PowerShell v2+, 85 bytes

```
param($a)!((,'('+$a[0..(($b=$a.length)/2-1)]+'0)-('+$a[($b/2)..$b]+'0)')-join'+'|iex)

```

Takes input `$a` as a string (necessary to support numbers `>2^64-1` without getting into extremely clunky `[biginteger]` casting on the command line).

For the explanation, let's assume input of `'1423'`. We're then constructing a new string. The two array slices are obvious (`$a[...]`), and that's surrounded by three additional strings `(`, `0)-(`, and `0)`, formulating an array of `char`s and `string`s. Note the `,` at the front to enforce array concatenation, not string concatenation.

That whole array is `-join`ed together with `+`, resulting in a string like `(+1+4+0)-(+2+3+0)`, and you can see that the `0`s are needed to prevent syntax errors. That's fed into `|iex` (short for `Invoke-Expression` and similar to `eval`), which will compute the mathematical result. So long as the string is balanced, you'll get `0` as an output, which we encapsulate in parens and take the Boolean-not thereof `!(...)`, to output `True`. If it's any non-zero integer, it'll output `False`.

### Test Cases

```
PS C:\Tools\Scripts\golfing> '1','6','11','141','23281453796004414','523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
1
True
---
6
True
---
11
True
---
141
True
---
23281453796004414
True
---
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True
---

PS C:\Tools\Scripts\golfing> '10','110','15421','5234095123508321','6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
10
False
---
110
False
---
15421
False
---
5234095123508321
False
---
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False
---

```
> 4 votes

# Answer
# C#, 83 bytes

```
n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

```

**Try it online!**

Full source, including test case:

```
using System;
using System.Numerics;

namespace BalancedNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<BigInteger,bool>s= n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

            Console.WriteLine(s(1));    //true
            Console.WriteLine(s(6));    //true
            Console.WriteLine(s(11));   //true
            Console.WriteLine(s(141));  //true
            Console.WriteLine(s(23281453796004414));    //true
            BigInteger bi = BigInteger.Parse("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088");
            Console.WriteLine(s(bi));   //true
            Console.WriteLine(s(10));   //false
            Console.WriteLine(s(12));   //false
            Console.WriteLine(s(110));  //false
            Console.WriteLine(s(15421));    //false
            Console.WriteLine(s(5234095123508321)); //false
            bi = BigInteger.Parse("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454");
            Console.WriteLine(s(bi));   //false
        }
    }
}

```

The BigInteger data type allows any number length. If the number is too large, the compiler complains (*error CS1021: Integral constant is too large*), so the **BigInteger.Parse(String)** method is used instead.

The solution can actually be reduced to **72 bytes** considering the input is a string (and updating the program accordingly):

```
t=>{int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

```
> 4 votes

# Answer
## Ruby, 63 bytes

```
->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}

```

Note: arg `s` must be string.

### Testing(minitest 5+ required):

```
require 'minitest/autorun'

class TestRunner < Minitest::Test
  def setup
    @truthy_nums = %w(1 6 11 141 23281453796004414 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
    @falsy_nums = %w(10 110 15421 5234095123508321 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454)

@f=->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}

  end
  def test_true
    @truthy_nums.each do |e|
      assert @f[e], e
    end
  end
  def test_false
    @falsy_nums.each do |e|
      assert !@f[e], e
    end
  end
end

```
> 4 votes

# Answer
# Perl, 29 bytes

Includes +5 for `-lpF`

Give number on STDIN

```
balanced.pl <<< 1423

```

`balanced.pl`:

```
#!/usr/bin/perl -lpF
$;+=$_-pop@F for@F;$_=!$

```
> 4 votes

# Answer
# Vyxal, 4 bytes

```
YIṠ≈

```

Try it Online!

Beats all other answers.

## How?

```
YIṠ≈
Y     # Interleave the input with itself, giving a list with each digit duplicated
 I    # Split into two halves
  Ṡ   # Sum each
   ≈  # Is this list all equal?

```

# 05AB1E, 6 bytes

```
.ι2äOË

```

Try it online!

Same concept.
> 4 votes

# Answer
# Brain-Flak, ~~410~~ ~~206~~ ~~204~~ 178 + 3 = 181 bytes

Here is a 178 byte version that uses the `-a` flag.

*26 bytes golfed off by DJMcMayhem*

Try it Online

```
([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){(<{}{}>)}{}({{}<>[{}]<>}<(())>){{}{}((<>))}{}

```

Here is a longer 410 byte version that does not use the `-a` flag.

Try it Online

```
{(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){{}{}(<>)}{}(([])<>)({<{}>{}<([])>}{}<>[{<{}>{}<([])>}{}]<(())>){{}{}((<>))}{}

```

# Explanation

Here is an explanation of the shorter solution

To begin the number is converted to all of its ASCII values by the `-a` flag.

We push the stack height (i.e. number of digits) and divide by two.

```
([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)

```

For each number less than the number we just pushed we move a digit to the other stack

```
{({}[()]<({}<>)<>>)}{}

```

If the stacks have different heights we remove the top item from the current stack

```
([]<>[[]]<>){(<{}{}>)}{}

```

We want the difference between the sums of each stack. So we use the following algorithm to sum each stack.

```
{{}}

```

This assumes no digit has an ASCII value of zero, which is a valid assumption.

We run this for both stacks and take the difference (The `<(())>` is necessary for the next part.

```
({{}}<>[{{}}]<(())>)

```

We now want to negate the sum. If the sum is zero it will pop the top off revealing the one we pushed earlier otherwise it will remove both the number and the one and place a zero on top.

```
{{}{}((<>))}{}

```
> 3 votes

# Answer
# Retina, ~~64~~ 44 bytes

```
^((.)*?).?(?=(?<-2>.)*$)
$1
\d
$*
^(1+) \1$

```

**Try it online**

The first stage splits the string in the middle, omitting the middle character if there is one (~~taken and modified from here.~~ Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length.
> 3 votes

# Answer
## JavaScript (ES6), ~~74~~ ~~67~~ ... ~~59~~ 50 bytes

Recursively sums the difference of the first and last digits until there's less than two digits left:

```
let f =

n=>!(F=n=>n[1]?(n.pop()-n.shift()+F(n)):0)([...n])

// some truthy examples
console.log(f("11"));
console.log(f("141"));
console.log(f("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"));

// some falsy examples
console.log(f("12"));
console.log(f("110"));
console.log(f("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"));
```
> 3 votes

# Answer
# R, ~~105~~ 96 bytes

Turns out R is very verbose. Takes input as a character.

```
function(x){y<-as.numeric(unlist(strsplit(x,"")));l<-length(y)%/%2;sum(tail(y,l))==sum(head(y,l))}

```

Formatted nicely:

```
function(x){
    y=as.numeric(unlist(strsplit(x,"")))
    l=length(y)%/%2
    sum(tail(y,l))==sum(head(y,l))
}

```

Explanation

* `y<-as.numeric(unlist(strsplit(x,"")))` Split the input (a string\_, and coerce it to a vector instead of a list, and then turn it back into integers.
* `sum(tail(y,`: `tail` takes the last *n* elements, found by:
    + `length(y)%/%2))`, where `%/%` is integer division, to get the ceiling of the quotient, where the length is odd.
* `sum(head(y,length(y)%/%2))`: like `tail`, `head` takes the first *n* elements of the vector, found in the same way.

## Edits

* Saved seven bytes thanks to niam
* Switched to `=` instead of `<-` , saved another two bytes.
> 3 votes

# Answer
# Actually, ~~17~~ 16 bytes

This answer is inspired by ElPedro's Python 2 answer and their idea to use `[-b:]`. Golfing suggestions welcome. Try it online!

```
$♂≈;l½L│±aHΣ)tΣ=

```

**Ungolfing**

```
      Implicit input n.
$♂≈   list(str(n)). This converts n to a list of n's digits.
;l    Duplicate the list of digits and get its length. Call it len.
½L    Push len//2.
│     This duplicates the stack.
        Stack: len//2, digit_list, len//2, digit_list
±     Negate the len//2 at TOS for later.
a     Invert the stack.
        Stack: digit_list, len//2, digit_list, -(len//2)
HΣ    Push digit_list[:len//2], then push its sum.
)     Rotate this first sum to BOS.
tΣ    Push digit_list[-(len//2):], then push its sum.
=     Check if those sums are equal.
      Implicit return.

```
> 3 votes

# Answer
# Perl 6,  ~~42 39~~  33 bytes

```
{[==] .comb[{^($_/2),Int($_/2)..*}]>>.sum}

```

Test it

```
{[==] .comb[^(*/2),(*/2).Int..*]>>.sum}

```

Test it

```
{[==] .comb[^*/2,^*/2+*/2]>>.sum}

```

Test it (from Jo King)

## Explanation:

```
{ # lambda with implicit parameter ｢$_｣

  [==]                   # reduce the following using &infix:«==»

    .comb\               # split input into individual characters
    [                    # index into that using:

      # first half of the values (includes middle value)
      # ｢(0/2) ..^ (*/2)｣
      ^ * / 2,

      # last half of the values (includes middle value)
      ^ * / 2            # same number of values as first half
        + * / 2          # shifted up by half

    ]\
    >>.sum               # sum each of the two halves separately
}

```
> 3 votes

# Answer
# PHP, ~~73~~ ~~67~~ ~~60~~ 57 bytes

Requires PHP 7.1 for negative string offsets:

```
for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;

```

Run:

```
echo 15324 | php -nR 'for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;';echo

```

# Previous version

Note: requires PHP 7 for the spaceship operator.

```
for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;

```

Run like this:

```
php -d error_reporting=30709 -r 'for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;' -- 15324;echo

```

## Explanation

Iterates over the digits in the number. Checks if the digit belongs to the first half or the second half (or is the middle digit) by comparing the digit's index to the length of the input with combined comparison (`2 * $x <=> $l - 1`). Then multiply that with the digit, take the sum of all digits. If it's a balanced number, the sum will be `0`.

Example with input `15324`:

```
  index     0  1  2  3  4
  digit     1  5  3  2  4

  2*index   0  2  4  6  8
  length-1  4  4  4  4  4
  factor    1  1  0 -1 -1  # Result of the spaceship operator

  result    1  5  0 -2 -4
           --------------
  sum                   0

```

# Tweaks

* Don't set the digit to `$d`, just iterate the length of the input. Saved 5 bytes.
* String offset `null` doesn't have to be cast to `int` for PHP to interpret it as `0`. Saved 1 byte.
* Using negative string offsets to get the digits from the second half and iterating to half of the string. Saved 7 bytes, but requires PHP 7.1
* Saved 3 bytes by using `$argn`
> 2 votes

# Answer
# Python 2, ~~83~~ 77 bytes

```
g=[int(h)for h in raw_input()];b=int(len(g)/2);print sum(g[:b])==sum(g[-b:])or b==0

```

**EDIT**

reduced to 77 with help from @Rod

```
g=[int(h)for h in raw_input()];b=len(g)/2;print sum(g[:b])==sum(g[-b:])or b<1

```

Examples:

```
D:\>bal.py
1
True

D:\>bal.py
6
True

D:\>bal.py
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True

D:\>bal.py
10
False

D:\>bal.py
110
False

D:\>bal.py
 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False

```
> 2 votes

# Answer
# Javascript, 73 bytes

Good ol' ES5 loops

```
for(a=c=0,b=(l=(s=prompt()).length)-1;a<~-l/2;c-=s[a++]-s[b--]);alert(!c)
```

What's happening here?

```
for(
    a=c=0,               // a = left digits of the number
                         // c = the result
    b=                   // b = right digits of number
        (l=              // l = length of number - 1
            (s=prompt()) // s = the number as input from user
        .length)-1;

    a<~-l/2;             // while a < length of number / 2, rounded down (~-)

    c-=
        s[a++]           // c -= left digit
        -
        s[b--]           // c += right digit (because - and - == +)
 );
                         // for balanced numbers c should be 0
 alert(!c)               // 0 equals false in javascript, so output the opposite of c

```
> 2 votes

# Answer
# Python 2, 73 bytes

```
def f(n):x=map(int,str(n));d=len(x)/2;print sum(x[:d])==sum(x[-d:])or d<1

```

Tests are at **ideone**

We have to use `str()` rather than \`\` since `n` may be outside the range of signed int.
> 2 votes

# Answer
## Clojure, ~~66~~ 64 bytes

Update: Took `str` out from the `map int` function.

```
(comp #(=(apply +(map -(drop(/(count %)2)%)%))0)#(map int %)str)

```

This would have been shorted if the input format was more flexible, now I had to first map the integer into a sequence of ASCII values. The inner `map` calculates pair-wise differences of values from the two halves, and this checks if the sum of deltas is zero.

`((comp f g h) x y z)` = `(f (g (h x y z))`.

Actually this ended up being the same length as just doing the mapping within a `let` and just define a single function.
> 2 votes

# Answer
# Factor \+ `math.unicode sequences.repeating`, 32 bytes

```
[ 2 repeat halves [ Σ ] same? ]

```

Try it online!

```
            ! "141"
2 repeat    ! "114411"
halves      ! "114" "411"
[ Σ ] same? ! t

```
> 2 votes

# Answer
# C (GCC), 66 bytes

```
char*c,*d;i;f(s){for(d=index(c=s,i=0);c<--d;)i+=*c++-*d;return!i;}

```

Try It Online!

Explanation:

```
char*c,*d;i;
f(s)
{
    // d = the first null-terminator in s, c = s, i = 0
    // Before the first and after each iteration, decrement d and break out of
    // the loop if c has surpassed d.
    for(d=index(c=s,i=0);c<--d;)
        // Add the ascii values of c and d to i, increment c.
        // The ascii values of a number equals the ascii value of 0 plus the
        // number, so if numbers j and k are respectively stored in c and d,
        // *c - *d = (i + '0') - ('j + '0') = i - j = the signed difference
        i+=*c++-*d;
    // If the sum of the signed differences are 0, return 1; otherwise 0
    return!i;
}

```
> 2 votes

# Answer
## Pyke, 20 bytes

```
[QleQ`)>[R<]mmbms$X!

```

Try it here!
> 1 votes

# Answer
## Mathematica, 69

```
Tr@#[[;;⌊l=Length@#/2⌋]]==Tr@#[[⌈l⌉+1;;]]&@*IntegerDigits

```
> 1 votes

# Answer
## Racket 204 bytes

```
(define(f n)(let*((s(number->string n))(g(λ(x y)(apply +(map(λ(x)(string->number(string x)))
(string->list(substring s x y))))))(l(string-length s))(h(/ l 2)))(if(=(g 0(floor h))(g(ceiling h)l))#t #f)))

```

Detailed version:

```
(define (f1 n)
(let* (  (s (number->string n))
         (g(λ(x y)
              (apply + (map
                        (λ(x)
                          (string->number
                           (string x)))
                        (string->list
                         (substring s x y))))))
         (l (string-length s))
         (h (/ l 2)))
    (if(= (g 0 (floor h)) (g (ceiling h) l))
       #t #f  ) ) )

```

Testing:

```
(f 23281453796004414)
(f 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
(f 15421)
(f 5234095123508321)

```

Output:

```
#t
#t
#f
#f

```
> 1 votes

# Answer
# sed (165 + 1 for -r) 166

```
/^.$/c1
:l;s,^([^!])([^!]*)([^!])!?([^=]*)=?(.*),\2!\4\1=\5\3,;tl;:
s,.?!|0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,;s,7,61,
s,8,71,;s,9,81,;t;s,1=1,=,;t;/^=$/c1
c0

```

Output:
1 for true
0 for false

Try it online!
> 1 votes

# Answer
# Python 2.7, 102 92 bytes

For loop works better :/

```
s=`input()`
a,b,l=0,0,len(s)
for i in range(l/2):a=a+int(s[i]);b=b+int(s[l-i-1])
print a==b

```

Same idea, just use length - i to get other side. It will never reach the center of an odd number.

Old code

```
s=input()
l=len(s)
def n(i):return 0if not i else int(i[0])+n(i[1:])
print n(s[:l/2])==n(s[l/2+l%2:])

```

Gets input
Saves length of input
Recursive func to get sum of string
Compare the first half sum to the second half sum

Trying to get it below 100, but its hard :/
> 1 votes

# Answer
# PHP, 66 Bytes

```
for(;2*$i<$l=strlen($t=$argv[1]);)$s+=$t[$i++]-$t[$l-$i];echo+!$s;

```

-4 Bytes by @Titus Thank You
> 1 votes

# Answer
# C function, 74

```
l;i;t;f(char *n){l=strlen(n);for(t=i=0;i<l/2;)t+=n[i]-n[l-++i];return !t;}

```

Ideone.
> 1 votes

# Answer
# Groovy - 74 69 bytes

Represented as a Groovy closure. Please note that the parameter passed in (i) is a String, as with the Java version.

```
{i->e=i.size();k=0;s=0;for(;s<e;){k+=i.charAt(s++)-i.charAt(--e)};!k}
```
> 1 votes

# Answer
# JavaScript (ES5), ~~70~~ 66 bytes

```
function g(n){for(a=b=0;(l=n.length)>b*2;)a+=n[b]-n[l-++b];return!a}

// tests:
var falses = ['10', '12', '110', '15421', '5234095123508321', '6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454']
var i=falses.length;
while(i--) console.info(!g(falses[i]) ? 'ok' : 'not false: ' + falses[i])

var trues = ['1', '6', '11', '141', '1221', '23281453796004414', '523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'];
i = trues.length;
while(i--) console.info(g(trues[i]) ? 'ok' : 'not true: ' + trues[i])
```
> 1 votes

# Answer
# Groovy (~~85~~ 73 Bytes)

```
f={n->x=n.collect{[it,it]}.flatten().collate(n.size())*.sum();x[0]==x[1]}

```
* `.collect{[it,it]}` \- Dupe all elements into a 2D array.
* `.flatten()` \- Turn 2D array into 1D array.
* `.collate(n.size())` \- Split new array in half.
* `*.sum()` \- Sum both sub-arrays.
* `x[0]==x[1]` \- Check for equality / return.
> 1 votes

# Answer
# Jelly, 7 bytes

```
Dx2ŒH§E

```

Try it online!

Same algorithm as 05AB1E answer.
> 1 votes

# Answer
# Python 3, ~~69~~ 67 bytes

I'm quite proud of this one, since it's smaller than any other python answers in this thread :). I owe the idea of printing the equivalence of the two sums to tuukkaX's answer though, I don't think I would have thought of that myself.

```
*a,=map(int,input())
h=(len(a)+1)//2
print(sum(a[:h])==sum(a[-h:]))

```

Try it online!

The `+1` on the second line is necessary to make my slices work properly for single digit inputs. I realised that even though it overslices, it does so on both sides so it still works.

On a list of len 1, slicing `a[:0]` gives an empty list but `a[-0;]` gives the whole list. Every 1 digit input became itself==0 so it was always false.

thanks to david for shaving off 2 bytes
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 58 bytes

```
s=>s.Zip(s.Reverse(),(a,b)=>a-b).Take(s.Length/2).Sum()==0

```

Try it online!
> 1 votes

# Answer
# C (gcc), 98 bytes

```
V=2;main(A,v)char**v;{char*a=*++v;while(a[1])a++;while(*v<a)V+=*(*v)++,A+=*a--;puts(A^V?"0":"1");}

```

There's a shorter submission for a C function, but mine compiles on its own and handles command line arguments.

Try it online!
> 1 votes

# Answer
# flax, 7 bytes

```
EṠXFz˘D

```

Port of the 05AB1E answer. Ties with jelly. No online link as the latest commit is not on ATO.

## Explanation

```
EṠXFz˘D

      D  ⊳ Digits
    z˘   ⊳ Zip with itself
   F     ⊳ Flatten
  X      ⊳ Split into two
EṠ       ⊳ Are the sum of the two halves equal?

```
> 1 votes

# Answer
# JavaScript ~~95~~ 88 bytes

```
i=>(s=(i,a,b)=>[...i.slice(a,b)].reduce((p,e)=>p-e,0))(i=i+"",0,m=i.length/2)==s(i,m+.5)

```

Explanation:

Convert input to a string, create a function that takes string segments and sums up all of the digits, and call that function for the left and right halves of the input.
> 0 votes

# Answer
# Scala, 77 bytes

Like Java, must take Strings.
I'm sure someone could find an improvement.

`def f(s:String)=(for(i<-0 until s.length/2)yield s(i)-s(s.length-i-1)).sum==0`

Can test online
> 0 votes

# Answer
# Tcl, 156 bytes

```
proc R n {set l [string le $n];puts [expr [join [split [string ra $n 0 [expr $l/2-($l%2==0)]] {}] +]==[join [split [string ra $n [expr $l/2] $l+$l] {}] +]]}

```

Try it online!
> 0 votes

# Answer
# Burlesque, 39 bytes

```
{iTg1!!}s9XXsa2./s1{q%9!{<-%9!}}M-)++sm

```

Try it online!

```
{
 iT   # Generate tails
 g1   # Get var 1
 !!   # Select from array
}s9   # Save as var 9
XX    # Split int to digits
sa    # Number of digits
2./   # /2
s1    # Save as 1
{
 q%9! # Eval 9 as function
 {
  <-  # Reverse
  %9! # Eval 9 as function
 }
}M-   # Eval each contained function on the digits
)++   # Map sum
sm    # Same

```
> 0 votes

# Answer
# Thunno `E`, \\$14\log\_{256}(96)\approx\\$ 11.52 bytes

```
eDZPiES2AP.Sze

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

```
    # E flag converts to string
e   # Map:
DZP #  Pair with itself
i   #  Convert to integer
E   # End map
S   # Flatten
2AP # Split in half
.S  # Sum each
ze  # All equal?

```
> 0 votes

---
Tags: code-golf, number
---


title: Sandbox overflow

text:
# Question
Title: Sandbox overflow
Your task is to output a square sandbox of size `n+2` with `/` characters in the corners and `|` for the sides, and `-` for the top, with `n**2` layers of sand (`.`) overflowing out of the sandbox of width `n+2`

# Testcases

```
1
->
/-/
|.|
/./
...

2
->
/--/
|..|
|..|
/../
....
....
....
....

3
->
/---/
|...|
|...|
|...|
/.../
.....
.....
.....
.....
.....
.....
.....
.....
.....

```

Trailing spaces and newlines are allowed

This is , so shortest code wins!

# Answer
> 2 votes
# Charcoal, 19 bytes

```
Ｎθ↶ＵＢ.×.×θθ/Ｆ³«θ↶²/

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input `n`.

Change the default drawing direction to up. (I do it here because I can use the default pivot of 90°.)

```
ＵＢ.

```

Set the default character for unpainted areas to `.`.

```
×.×θθ

```

Draw the right-hand edge of the overflowing sand. (The rest of the sand gets drawn as part of the unpainted area.)

```
/

```

Draw the bottom right `/`.

```
Ｆ³«

```

Repeat three times.

```
θ

```

Draw the right `|`s, the top `-`s or the left `|`s as appropriate.

```
↶²

```

Pivot the default drawing direction by another 90°.

```
/

```

Draw the top right, top left or bottom right `/` as appropriate.

# Answer
> 5 votes
# Python 2, 81 bytes

```
n=input()
i=2
while~n*n<i:i-=1;d='/.|'[~-i*(i+n)and~(i<-n)];print d+'-.'[i<1]*n+d

```

Try it online!

# Answer
> 5 votes
# Python, 69 bytes

```
lambda n:[f"/{'-'*n}/",*n*[f"|{(c:='.'*n)}|"],f"/{c}/",*n*n*[c+'..']]
```

Attempt This Online!

-2 bytes thanks to @ophact.

Outputs a list of lines, as allowed by standard I/O rules.

# Answer
> 4 votes
# 05AB1E (legacy), ~~30~~ 29 bytes

```
'-×'/.ø©Ð„|.‡I.D®W'.:ÐW‡In.D»

```

Uses the legacy version of 05AB1E because it can take the minimum character of a string (based on its unicode value), saving 2 bytes over repushing the characters.

Try it online or verify all test cases.

**Explanation:**

```
'-×      '# Repeat "-" the (implicit) input amount of times as string
   '/.ø  '# Surround it with leading/trailing "/"
       ©  # Store this string in variable `®` (without popping)
Ð         # Triplicate it
 „|.‡     # Transliterate the "/" to "|" and "-" to "." in the other copy (the
          # transliterate ignores the trailing "…---/" since the strings are
          # of unequal length)
     I.D  # Duplicate it the input amount of times
®         # Push string `®`
 W        # Push the minimum (without popping): "-"
  '.:    '# Replace all "-" with "." in string `®`
Ð         # Triplicate it
 W        # Push the minimum (without popping): "."
  ‡       # Replace all "/" with "." (transliterate again ignores the trailing
          # "…---/")
   In     # Push the input, and square it
     .D   # Duplicate this string of "."s that many times
»         # Join all strings on the stack by newlines
          # (after which the result is output implicitly)

```

# Answer
> 4 votes
# Excel, ~~96~~ 95 bytes

```
=LET(r,REPT(".",A1),"/"&REPT("-",A1)&"/"&REPT("
|"&r&"|",A1)&"
/"&r&"/
"&REPT("."&r&".
",A1^2))

```

# Answer
> 3 votes
# Java 11, 121 bytes

```
n->"/"+"-".repeat(n)+"/\n"+("|"+".".repeat(n)+"|\n").repeat(n)+"/"+".".repeat(n)+"/\n"+(".".repeat(n+2)+"\n").repeat(n*n)

```

Try it online.

Straight-forward approach using Java 11+'s `String#repeat`.

# Answer
> 3 votes
# APL+WIN, 58 bytes

Prompts for n

```
o,(⍉(n,⍴c)⍴c←'-',((n+1)+n*2)⍴'.'),o←(1,n,1,(n←⎕)*2)/'/|/.'

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# Retina, 42 bytes

```
.+
/$&*-/¶$&*$(|$&*.|¶)/$&*./$&**$(¶.$&*..

```

Try it online! Link includes test cases. Explanation: Straightforward application of Retina 1's string repeat operator, except that `**` is shorthand for `*$&*` thus squaring the input.

# Answer
> 2 votes
# JavaScript (Node.js), 77 bytes

```
n=>`/${(C=D=>D.repeat(n))('-')}/
${C(`|${a=C('.')}|
`)}/${a}/
`+C(C(a+`..
`))

```

Try it online!

Constructs a large template string using a function `C` to shorten the usage of `repeat`.

Thanks @Arnauld for -4 bytes by reminding me that literal linefeeds exist. (I've been doing way too much Python recently.)

# Answer
> 1 votes
# C (GCC), ~~143~~ 137 bytes

*saved 6 bytes thanks to @ceilingcat*

```
j;main(n){scanf("%d",&n);char s[n+=2];for(;j<n;puts(s))memset(s,46-!j,n),*s=s[n-1]="/|"[j++&&j^n];*s=s[--n]=46;for(j=--n*n;j--;)puts(s);}

```

Try it online!

Indented version:

```
j;
main(n){
    scanf("%d",&n);
    char s[n+=2];
    for(;j<n;puts(s))
        memset(s,46-!j,n),
        *s=s[n-1]="/|"[j++&&j^n];
    *s=s[--n]=46;for(j=--n*n;j--;)puts(s);
}

```

# Answer
> 1 votes
# Rust, ~~140~~ 134 bytes

```
|i|{let r=".".repeat(i);print!("/{}/
{}/{}/
{}
","-".repeat(i),format!("|{}|
",r).repeat(i),r,(".".repeat(i+2)+"
").repeat(i.pow(2)))}

```

Try it online!

**To 134 bytes:** I was able to save 6 bytes by using type hinting.

The link includes a header and a footer for calling the closure, and I call it for `1`, `2`, and `3`, to prove that it works!

# Answer
> 1 votes
# Vyxal `J`, 32 bytes

```
¤-\/pǏD£‛/-‛|.Ŀ⁰Ḋ¥:g\.VDg\/$V⁰²Ḋ

```

Try it Online!

## How?

```
¤-\/pǏD£‛/-‛|.Ŀ⁰Ḋ¥:g\.VDg\/$V⁰²Ḋ
¤                                # Push an empty string
 -                               # Push "-" * a + b (where a is the (implicit) input, and b is the empty string)
  \/p                            # Prepend "/"
     Ǐ                           # Append its first character (the slash)
      D                          # Triplicate
       £                         # Pop and store in the register
        ‛/-                      # Push string "/-"
           ‛|.                   # Push string "|." (for input 3, stack e.g. ["/---/", "/---/", "/-", "|."])
              Ŀ                  # Transliterate (stack e.g. ["/---/", "|...|"])
               ⁰Ḋ                # Duplicate the top value of the stack the input amount of times (stack e.g. ["/---/", "|...|", "|...|", "|...|"])
                 ¥               # Push contents of register (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/"])
                  :              # Duplicate (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/", "/---/"])
                   g             # Take the minimum by character code, which is "-" (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/---/", "-"])
                    \.V          # Replace with a period (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../"])
                       D         # Triplicate (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "/.../"])
                        g        # Take the minimum by character code, which is "." (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "."])
                         \/      # Push "/"
                           $     # Swap with the period (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "/.../", "/", "."])
                            V    # Replace (stack e.g. ["/---/", "|...|", "|...|", "|...|", "/.../", "....."])
                             ⁰²  # Push the input squared
                               Ḋ # Duplicate the top value of the stack that many times
                                 # J flag joins the stack by newlines

```

# Answer
> 0 votes
# MathGolf, 37 bytes

```
'.*'|▌'|+k(Ä_'-k*'/▌'/+_¬'.k⌠*k²(Ä_]n

```

Try it online.

**Explanation:**

```
'.*    '# Push a string with the (implicit) input amount of "."
'|▌    '# Prepend "|"
'|+    '# Append "|"
k(Ä     # Loop the input-1 amount of times,
        # using a single character as inner code-block:
   _    #  Duplicate the "|...|" string
'-k*   '# Push a string with the input amount of "-"
'/▌'/+  # Surround it with leading "/"
_       # Duplicate it
 ¬      # Rotate the items on the entire stack once
'.k⌠*  '# Push a string with the input+2 amount of "."
k²(Ä    # Loop input²-1 amount of times,
        #  using a single character as inner code-block:
    _   #  Duplicate the "." string
]       # Wrap the stack into a list
 n      # Join this list with newline delimiter
        # (after which the entire stack is output implicitly)

```

# Answer
> 0 votes
# Perl 5 \+ `-pl`, 66 bytes

```
$;=c x$_;$_=a."-"x$_.ad."b$;bd"x$_.a.$;.a."dcc$;"x$_**2;y;a-d;/|..
```

Try it online!

## Explanation

Generates the output, char by char, replacing characters used multiple times with bareword letters to avoid additional quotes or brackets. Makes use of operator precedence in that `x**y` works without quotes, but `x*x` doesn't. Also makes use of the fact that `-p` adds `;}` to the code and uses `;` as the separator for `y///`, saving another byte.

# Answer
> 0 votes
# MATL, 38 bytes

```
QQttGU+&O46+47blht&(45G:Q(!'|'5MlOh&(c

```

Try it online!

---
Tags: code-golf, string, ascii-art
---


title: Sum of Modulo Sums

text:
# Question
Title: Sum of Modulo Sums
Given an integer `n > 9`, for each possible insertion between digits in that integer, insert an addition `+` and evaluate. Then, take the original number modulo those results. Output the sum total of these operations.

An example with `n = 47852`:

```
47852 % (4785+2) = 4769
47852 % (478+52) =  152
47852 % (47+852) =  205
47852 % (4+7852) =  716
                  -----
                   5842

```

### Input

A single positive integer in any convenient format, `n > 9`.

### Output

The single integer output following the above construction technique.

### Rules

* You don't need to worry about input larger than your language's default type.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
47852 -> 5842
13 -> 1
111 -> 6
12345 -> 2097
54321 -> 8331
3729105472 -> 505598476

```

# Answer
> 12 votes
# 05AB1E, ~~12~~ 10 bytes

```
v¹¹N¹‚£O%O

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 11 votes
# JavaScript, ~~43~~ 47 bytes

```
f=
n=>eval(n.replace(/./g,'+'+n+"%($`+ +'$&$'')"))

I.oninput=_=>O.value=f(I.value)
```

```
<input id=I>
<input id=O disabled>
```

Takes input as string.

---

Edit:

**+4 bytes**: Leading zeroes in JavaScript converts the number to octal ):

# Answer
> 8 votes
# Brachylog v1, 20 bytes

```
:{$@~c#C:@$a+:?r%}f+

```

Try it online!

### Explanation

This implements the formula given. The only thing we have to be careful about is when a `0` is in the middle of the input: in that case Brachylog gets pretty quirky, for example it won't accept that a list of integers starting with a `0` can be concatenated into an integer (which would require ignoring the leading `0` — this is mainly programmed that way to avoid infinite loops). Therefore to circumvent that problem, we convert the input to a string and then convert back all splitted inputs into integers.

```
                       Example Input: 47852

:{               }f    Find all outputs of that predicate: [716,205,152,4769]
  $@                     Integer to String: "47852"
    ~c#C                 #C is a list of two strings which when concatenated yield the Input
                           e.g. ["47","852"]. Leave choice points for all possibilities.
        :@$a             Apply String to integer: [47,852]
            +            Sum: 899
             :?r%        Input modulo that result: 205
                   +   Sum all elements of that list

```

# Answer
> 7 votes
# ES6 (Javascript), ~~42~~, 40 bytes

EDITS:

* Got rid of *s*, -2 bytes

**Golfed**

```
M=(m,x=10)=>x<m&&m%(m%x+m/x|0)+M(m,x*10)

```

**Test**

```
M=(m,x=10)=>x<m&&m%(m%x+m/x|0)+M(m,x*10);

[47852,13,111,12345,54321,3729105472].map(x=>console.log(M(x)));
```

# Answer
> 7 votes
# Jelly, 12 bytes

```
ŒṖṖLÐṂḌS€⁸%S

```

**TryItOnline!**

### How?

```
ŒṖṖLÐṂḌS€⁸%S - Main link: n
ŒṖ           - partitions (implicitly treats the integer n as a list of digits)
  Ṗ          - pop - remove the last partition (the one with length one)
    ÐṂ       - keep those with minimal...
   L         - length (now we have all partitions of length 2)
      Ḍ      - undecimal (convert each entry back to an integer)
       S€    - sum each (add the pairs up)
         ⁸   - left argument, n
          %  - mod (vectorises)
           S - sum

```

# Answer
> 6 votes
## Python 2, 45 bytes

```
f=lambda n,c=10:n/c and n%(n/c+n%c)+f(n,c*10)

```

Uses arithmetic rather than strings to divide the input `n` into parts `n/c` and `n%c`, which `c` recurses through powers of 10.

# Answer
> 5 votes
## Python 2, ~~68~~ ~~64~~ 68 bytes

-4 bytes thanks to atlasologist

```
lambda x:sum(int(x)%(int(x[:i])+int(x[i:]))for i in range(1,len(x)))

```

\*Input is a string

# Answer
> 5 votes
# C 77 + 4 = 81 bytes

### golfed

```
i,N,t,r,m;f(n){for(r=0,m=n;n;t=n%10,n/=10,N+=t*pow(10,i++),r+=m%(n+N));return r;}

```

### Ungolfed

```
#include<stdio.h>
#include<math.h>

i,N,t,r,m;

f(n)
{
    m=n;
    r=0;
    while(n)
    {
        t=n%10;
        n/=10;
        N+=t*pow(10,i++);
        r+=m%(n+N);
    }
    return r;
}

main()
{
    printf("%d",f(47852));
}

```

# Answer
> 5 votes
# Perl ~~35 32~~ 27 Bytes

Includes +3 for `-p`

Saved 8 bytes thanks to Dada

```
$\+=$_%($`+$')while//g}{

```

# Answer
> 4 votes
# C, 59 bytes

```
t,s;f(n){s=0;t=10;while(t<n)s+=n%(n/t+n%t),t*=10;return s;}

```

`t` is `10,100,1000,...` and represents the cut in the big number. `n/t` is the right part and `n%t` the left part. If `t` is bigger than the number, it is finished.

Ungolfed and usage:

```
t,s;
f(n){
 s=0;
 t=10;
 while(t<n)
  s += n % (n/t + n%t),
  t *= 10;
 return s;
}

main(){
 printf("%d\n",f(47852));
}

```

# Answer
> 3 votes
## Retina, 38 bytes

Byte count assumes ISO 8859-1 encoding.

```
\B
,$';$_¶$`
G-2`
\d+|,
$*
(1+);\1*

1

```

Not exactly efficient...

Try it online! (The first line enables a linefeed-separated test suite.)

### Explanation

```
\B
,$';$_¶$`

```

Between every pair of characters, we insert a comma, everything in front of the match, a semicolon, the entire input, a linefeed, and everything after the match. For input `12345` this gives us:

```
1,2345;12345
12,345;12345
123,45;12345
1234,5;12345
12345

```

I.e. every possible splitting of the input along with a pair of the input. We don't need that last line though so:

```
G-2`

```

We discard it.

```
\d+|,
$*

```

This replaces each number as well as the comma with its unary representation. Since the comma isn't a number, it's treated as zero and simply removed. This adds the two parts in each splitting.

```
(1+);\1*

```

This computes the modulo by removing all copies of the first number from the second number.

```
1

```

That's it, we simply count how many `1`s are left in the string and print that as the result.

# Answer
> 3 votes
# Pyth, 14 bytes

```
s.e%QssMc`Q]k`

```

A program that takes input of an integer and prints the result.

Test suite

**How it works**

```
s.e%QssMc`Q]k`   Program. Input: Q
s.e%QssMc`Q]k`Q  Implicit input fill
 .e          `Q  Map over str(Q) with k as 0-indexed index:
        c`Q]k     Split str(Q) into two parts at index k
      sM          Convert both elements to integers
     s            Sum
   %Q             Q % that
s                Sum
                 Implicitly print

```

# Answer
> 3 votes
## Haskell, 62 bytes

```
f x|m<-mod x=sum[m$div x(10^k)+m(10^k)|(k,_)<-zip[0..]$show x]

```

Defines a function `f`. See it pass all test cases.

# Answer
> 3 votes
# Perl 6, 33 bytes

```
{sum $_ X%m:ex/^(.+)(.+)$/».sum}

```

## Expanded:

```
{                  # bare block lambda with implicit parameter ｢$_｣

  sum

    $_             # the input

    X%             # cross modulus

    m :exhaustive /  # all possible ways to segment the input
      ^
      (.+)
      (.+)
      $
    /».sum         # sum the pairs
}

```

# Answer
> 3 votes
## Mathematica, 75 bytes

```
Tr@ReplaceList[IntegerDigits@#,{a__,b__}:>Mod[#,FromDigits/@({a}+{b}+{})]]&

```

This uses pattern matching on the list of digits to extract all partitions of them into two parts. Each such partition into `a` and `b` is then replaced with

```
Mod[#,FromDigits/@({a}+{b}+{})]

```

The notable thing here is that sums of lists of unequal length remain unevaluated, so e.g. if `a` is `1,2` and `b` is `3,4,5` then we first replace this with `{1,2} + {3,4,5} + {}`. The last term is there to ensure that it still remains unevaluated when we evenly split an even number of digits. Now the `Map` operation in Mathematica is sufficiently generalised that it works with any kind of expression, not just lists. So if we map `FromDigits` over this sum, it will turn each of those lists back into a number. At that point, the expression is a sum of integers, which now gets evaluated. This saves a byte over the more conventional solution `Tr[FromDigits/@{{a},{b}}]` which converts the two lists first and then sums up the result.

# Answer
> 3 votes
# Actually, ~~16~~ 15 bytes

Golfing suggestions welcome! Try it online!

**Edit:** -1 byte thanks to Teal pelican.

```
;╗$lr`╤╜d+╜%`MΣ

```

**Ungolfing**

```
         Implicit input n.
;╗       Save a copy of n to register 0.
$l       Yield the number of digits the number has, len_digits.
r        Yield the range from 0 to len_digits - 1, inclusive.
`...`M   Map the following function over that range, with variable x.
  ╤        Yield 10**x.
  ╜        Push a copy of n from register 0.
  d        Push divmod(n, 10**x).
  +        Add the div to the mod.
  ╜        Push a copy of n from register 0.
  %        Vectorized modulo n % x, where x is a member of parition_sums.
         This function will yield a list of modulos.
Σ        Sum the results together.
         Implicit return.

```

# Answer
> 3 votes
# Prolog (SWI), 63 bytes

```
N+C+M:-N>C,N+C*10+T,M is N mod(N//C+N mod C)+T;M=0.
N-M:-N+1+M.

```

Try it online!

-1 thanks to Jo King

More interesting:

# Prolog (SWI), 104 bytes

```
X/Y:-number_codes(X,Y).
N-M:-findall(N mod(A+B),(N/C,append(X,Y,C),X\=[],Y\=[],A/X,B/Y),L),sumlist(L,M).

```

Try it online!

# Answer
> 2 votes
# Ruby, 64 bytes

```
->s{s.size.times.reduce{|a,i|a+s.to_i%eval(s[0,i]+?++s[i..-1])}}

```

Takes the input as a string

# Answer
> 2 votes
# Befunge, ~~101~~ 96 bytes

```
&10v
`#v_00p:::v>+%\00g1+:9
*v$v+55g00</|_\55+
\<$>>\1-:v ^<^!:-1
+^+^*+55\_$%\00g55
.@>+++++++

```

Try it online!

**Explanation**

```
&              Read n from stdin.
100p           Initialise the current digit number to 1.

               -- The main loop starts here --

:::            Make several duplicates of n for later manipulation.

v+55g00<       Starting top right, and ending bottom right, this
>>\1-:v          routine calculates 10 to the power of the
^*+55\_$         current digit number.

%              The modulo of this number gives us the initial digits.
\              Swap another copy of n to the top of the stack.

_\55+*v        Starting bottom left and ending top left, this
^!:-1\<          is another calculation of 10 to the power of
00g55+^          the current digit number.

/              Dividing by this number gives us the remaining digits.
+              Add the two sets of digits together.
%              Calculate n modulo this sum.
\              Swap the result down the stack bringing n back to the top.

00g1+          Add 1 to the current digit number.
:9`#v_         Test if that is greater than 9.
00p            If not, save it and repeat the main loop.

               -- The main loop ends here --

$$             Clear the digit number and N from the stack.
++++++++       Sum all the values that were calculated.
.@             Output the result and exit.

```

# Answer
> 2 votes
# APL, 29 bytes

```
{+/⍵|⍨{(⍎⍵↑R)+⍎⍵↓R}¨⍳⍴1↓R←⍕⍵}

```

`⎕IO` must be `1`. Explanation (I'm not good at explaining, any imporvements to this are **very** welcome):

```
{+/⍵|⍨{(⍎⍵↑R)+⍎⍵↓R}¨⍳⍴1↓R←⍕⍵}
{                           } - Function (Monadic - 1 argument)
                           ⍵  - The argument to the function
                          ⍕   - As a string
                        R←    - Stored in R
                      1↓      - All except the first element
                    ⍳⍴        - 1 to the length
      {           }           - Another function
               ⍵↓R            - R without ⍵ (argument of inner function) leading digits
              ⍎               - As a number
             +                - Plus
       (    )                 - Grouping
         ⍵↑R                  - The first ⍵ digits of R
        ⍎                     - As a number
                   ¨          - Applied to each argument
   ⍵|⍨                        - That modulo ⍵ (outer function argument)
 +/                           - Sum

```

# Answer
> 2 votes
# C#, 67 bytes

```
n=>{long d=n,s=0,p=1;while(d>9)s+=n%((d/=10)+n%(p*=10));return s;};

```

Full program with ungolfed, explained method and test cases:

```
using System;

public class Program
{
    public static void Main()
    {
        Func<long,long> f=
        n=>
        {
            long d = n, // stores the initial number
                 r,         // remainder, stores the last digits
                 s = 0, // the sum which will be returned
                 p = 1; // used to extract the last digit(s) of the number through a modulo operation
            while ( d > 9 ) // while the number has more than 1 digit
            {
                d /= 10;    // divides the current number by 10 to remove its last digit
                p *= 10;    // multiplies this value by 10
                r = n % p;  // calculates the remainder, thus including the just removed digit
                s += n % (d + r);   // adds the curent modulo to the sum
            }
            return s;   // we return the sum
        };

        // test cases:
        Console.WriteLine(f(47852)); //5842
        Console.WriteLine(f(13));   // 1
        Console.WriteLine(f(111));  // 6
        Console.WriteLine(f(12345));    // 2097
        Console.WriteLine(f(54321));    // 8331
        Console.WriteLine(f(3729105472));   // 505598476
    }
}

```

# Answer
> 2 votes
# Attache, 48 bytes

```
Sum@{N[_]%Sum@Map[N]=>SplitAt[_,1..#_-1]}@Digits

```

Try it online!

## Explanation

```
Sum@{N[_]%Sum@Map[N]=>SplitAt[_,1..#_-1]}@Digits
                                          Digits    convert input to digits
    {                                   }@          call lambda with digits as argument
                      SplitAt[_,1..#_-1]            split digits at each partition
              Map[N]=>                              Map N to two-deep elements
          Sum@                                      Takes the sum of each sub array
     N[_]%                                          convert digits to int and vector mod
Sum@                                                sum the resultant array

```

# Answer
> 2 votes
# Pip, 15 bytes

```
a%$+(a^@_)MS,#a

```

Try It Online!

### Explanation

```
a%$+(a^@_)MS,#a
              a  Program argument: the input number
            ,#   Range(length)
          MS     Map this function to each of those numbers and sum the results:
     a^@_          Split the input number at that index
  $+(    )         Sum the two halves
a%                 Take the input number modulo the sum

```

Using range(len) as the list of indices to split on means that in addition to `4785+2`, `478+52`, `47+852`, and `4+7852`, we also have `+47852`. However, a number modulo itself is 0, which doesn't change the sum, so that's no problem.

# Answer
> 1 votes
**Clojure, ~~91~~ 81 bytes**

Edit: this is shorter as it declares an anonymous function `(fn[v](->> ...))` and not using `->>` macro although it was easier to read and call that way.

```
(fn[v](apply +(map #(mod v(+(quot v %)(mod v %)))(take 10(iterate #(* 10 %)1)))))

```

Original:

```
(defn s[v](->> 1(iterate #(* 10 %))(take 10)(map #(mod v(+(quot v %)(mod v %))))(apply +)))

```

Generates a sequence of 1, 10, 100, ... and takes first 10 items (assuming input values are less than 10^11), maps to modulos as specified in specs and calculates the sum. Long function names makes this solution quite long but at least even the golfed version should be quite easy to follow.

First I tried juggling strings around but it required tons of boilerplate.

# Answer
> 1 votes
## Racket 134 bytes

```
(let((s(number->string n))(h string->number)(g substring))(for/sum((i(range 1(string-length s))))(modulo n(+(h(g s 0 i))(h(g s i))))))

```

Ungolfed:

```
(define (f n)
  (let ((s (number->string n))
        (h string->number)
        (g substring))
    (for/sum ((i (range 1 (string-length s))))
      (modulo n (+ (h (g s 0 i)) (h (g s i)))))))

```

Testing:

```
(f 47852)
(f 13)
(f 111)
(f 12345)
(f 54321)
(f 3729105472)

```

Output:

```
5842
1
6
2097
8331
505598476

```

# Answer
> 1 votes
## Ruby 45 Bytes

```
->q{t=0;q.times{|x|p=10**x;t+=q%(q/p+q%p)};t}

```

This is a really neat solution. It is technically correct, but it is super inefficient. It would be much more efficient to write q.to\_s.size.times{...}. We use q.times because it saves characters, and the extra number of times it goes through the proc the expression just evaluates to zero.

# Answer
> 1 votes
# , 50 bytes

```
function(n)sum(n%%(n%%10^(x=1:nchar(n))+n%/%10^x))

```

Try it online!

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 92 bytes

```
	N =INPUT
S	N LEN(X) . L REM . R	:F(O)
	S =S + REMDR(N,L + R)
	X =X + 1	:(S)
O	OUTPUT =S
END

```

Try it online!

# Answer
> 1 votes
# K (oK), 31 bytes

**Solution:**

```
+/(+/+.:''1_(0,'!#$x)_\:$x)!'x:

```

Try it online!

**Example:**

```
+/(+/+.:''1_(0,'!#$x)_\:$x)!'x:47852
5842

```

**Explanation:**

Most of the code goes to building up the lists out of the input. Am wondering if there is a trick I'm missing.

```
{.:''1_(0,'!#$x)_\:$x}47852
(4 7852
47 852
478 52
4785 2)

```

Full breakdown:

```
+/(+/+.:''1_(0,'!#$x)_\:$x)!'x: / the solution
                             x: / store input as variable x
                           !'   / mod (!) each-both (')
  (                       )     / do this together
                        $x      / string x
                     _\:        / cut (_) each-left (\:)
            (       )           / do this together
                  $x            / string x
                 #              / count length of the string
                !               / til, range 0..n-1
             0,'                / prepend 0 to each
          1_                    / drop the first one
      .:''                      / value (.:) each-each (nested)
     +                          / flip rows and columns
   +/                           / sum up the columns
+/                              / sum up results of the modulo

```

# Answer
> 1 votes
# Vyxal `s`, ~~14~~ 11 bytes

*-3 bytes thanks to Lyxal*

```
żðvṀṪƛĖ+?$%

```

Try it online, or verify all test cases.

Explanation:

```
ż            # Range from 1 to the length of the input
  v          # Map each of those to
 ð           # A space
   Ṁ         # Inserted into the input at the nth index (resulting in ["4 7852", "47 852", "478 52", ...])
    Ṫ        # Remove the last one (which has doesn't space)
     ƛ       # On each string with the inserted space:
      Ė      #   Evaluate it as Vyxal code (so push both numbers in the string to the stack)
       +     #   Add them
        ?    #   Push the input
         $   #   Swap the top two items
          %  #   Modulo
             # Sum with the s flag

```

# Answer
> 1 votes
# Jelly, 9 bytes

```
œṖ€DḌ§⁸%S

```

Try it online!

Times out on most of the test cases, but agrees with existing solutions on smaller ones. The equivalent `DLœṖ€DḌ§⁸%S` (for 11 bytes) is considerably faster.

```
œṖ           Partition
   D         the digits of n
  €          at each [1 .. n], individually.
    Ḍ        Convert each digit slice in each partition back from digits.
     §       Sum each partition,
      ⁸%     take n mod each sum,
        S    and sum the sums.

```

Generates a large number of extra partitions all of which sum back to the original \\$n\\$, which don't affect the final sum because \\$n \mod n = n\\$.

# Answer
> 1 votes
# Arturo, 52 bytes

```
$[n][∑map 1..-size n 1=>[do~"|n|%"++insert n&"+"]]

```

Try it

# Answer
> 0 votes
# PHP, 60 bytes

```
for($n=1;($n*=10)<$a=$argn;)$r+=$a%(($a/$n^0)+$a%$n);echo$r;

```

Try it online!

# Answer
> 0 votes
# Java 8, ~~127~~ 66 bytes

```
n->{long m=n,r=0,p=1;for(;m>9;r+=n%((m/=10)+n%(p*=10)));return r;}

```

-61 bytes by creating a port of *@adrianmp*'s C# answer.

Try it here.

# Answer
> 0 votes
# Japt, ~~11~~ 10 bytes

```
¬x@%OvUi+Y

```

Try it

---

## Explanation

```
               :Implicit input of string U
¬              :Split to an array of characters
  @            :Pass each character at index Y through a function
      Ui+Y     :  Insert a + in U at index Y
    Ov         :  Evaluate as Japt
   %           :  Modulo U by the above
 x             :Reduce by addition

```

# Answer
> 0 votes
# Pari/GP, 42 bytes

```
n->sum(i=1,logint(n,10),n%(n\10^i+n%10^i))

```

Try it online!

# Answer
> 0 votes
# brev, 81 bytes

```
(c(fn(if(> x y)0(+(f(* x 10)y)(modulo y((compose + quotient&remainder)y x)))))10)

```

Usually the only other languages I can beat are other lisps ♀

---
Tags: code-golf, math, number-theory
---


# Question
Title: Sum of integers in string, separated by non-numericals such as 'a' and 'Y'
Create a program which sums all integers found in a string which is set as a variable in the program (thus, the program doesn't have to handle any input). The integer numbers are separated by non-numericals (anything but 0, 1, 2, 3, ..., 9).

Examples:

* `e7rde f ,fe 43 jfj 54f4sD` = 7+43+54+4=108
* `5` = 5
* `64 545,5445-32JIFk0ddk` = 64+545+5445+32+0=6086
* `0ab0` = 0+0 = 0

Extra notes:

* Unicode support is **not** necessary, but allowed
* `-n` (where `n` is an integer) is **not** counted as a negative `n`, but as a hyphen followed by `n`.

The answer may be printed on the screen (but not required).

Shortest answer (in characters) win.

# Answer
> 11 votes
## Perl, 15

Input in `$_`, sum in `$c`:

```
s/\d+/$c+=$&/ge

```

# Answer
> 14 votes
## Ruby 1.9, 21 characters

```
eval a.scan(/\d+/)*?+

```

To print the solution to stdout, 2 additional characters are required:

```
p eval a.scan(/\d+/)*?+

```

And to read from stdin instead of using a predefined variable, another 3 characters have to be used:

```
p eval gets.scan(/\d+/)*?+

```

For Ruby 1.8, replace `?+` with `"+"` to get a working solution in 22 characters.

# Answer
> 7 votes
# Ruby - 36 34 chars

```
s.scan(/\d+/).map(&:to_i).reduce:+

```

36 chars if you want the result printed.

```
p s.scan(/\d+/).map(&:to_i).reduce:+

```

Assumes the input is present as a string in s.

# Answer
> 6 votes
## Python (60)

```
import re;print sum(map(int,filter(len,re.split(r'\D',s))))

```

# Answer
> 4 votes
# JavaScript (ES6), 30

```
c=0,s.replace(/\d+/g,d=>c+=+d)

```

Annotated version:

```
// Store the sum.
c=0,
// Process every number found in the `s`.
s.replace(/\d+/g,
  // Convert the number into an integer.
  // Add it to the sum.
  d => c += +d
)

```

# Answer
> 3 votes
## Windows PowerShell, 23 ~~25~~ ~~29~~ ~~31~~

With output.

```
$x-replace'\D','+0'|iex

```

In fact, without output is exactly the same, you'd just pipe it somewhere else where it's needed.

# Answer
> 3 votes
# JavaScript \[31 bytes\]

```
eval(s.match(/\d+/g).join('+'))

```

# Answer
> 3 votes
# gs2, 4 bytes

```
W#Θd

```

Encoded in CP437; the third byte is `E9`.

`W` reads all numbers `/-?\d+/` from a string,  maps absolute value, `d` sums.

*(gs2, too, is newer than this challenge, but its `read-nums` command is a total coincidence.)*

# Answer
> 2 votes
## J - 40 38 characters

Lazy version. Requires the string library.

```
+/".(,' ',.~a.-.'0123456789')charsub y

```

# Answer
> 2 votes
## Java

out of the contest ;)

```
public static long sum(String s) {
    long sum = 0;
    String p = "";
    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        boolean c = false;
        if (Character.isDigit(ch[i])) {
            if (i + 1 < ch.length) {
                if (Character.isDigit(ch[i + 1])) {
                    p += ch[i];
                    c = true;
                }
            }
            if (!c) {
                p += ch[i];
                sum += Integer.valueOf(p);
                p = "";
                c = false;
            }
        }
    }
    return sum;
}

```

# Answer
> 2 votes
# Labyrinth, ~~29~~ 21 bytes

*(Disclaimer: Labyrinth is newer than this challenge.)*

Also, Labyrinth doesn't have variables, so I went with a normal input/output program.

```
)_"+`
( "?"
";;,;;(!@

```

This was fairly simple because of the way Labyrinth's input commands work. `?` tries to read a signed integer from STDIN and stops at the first non-digit. If it can't read an integer (because the next character is a `-` not followed by a digit, or any other non-digit, or we've reached EOF), it will return `0` instead. `,` on the other hand reads any subsequent byte and pushes the byte value. If this one is called at EOF it will return `-1` instead.

So here's some pseudocode for the solution:

```
running total = 0
while(true)
  while(true)
    try reading a non-zero integer N with ?
    if(N < 0)
      running total -= N
    else if(N > 0)
      running total += N
    else
      break
  // We've either read a zero or hit a something that isn't a number
  try reading a character with ,
  if(that returned -1)
    break
print running total

```

Dealing with negative numbers correctly complicates this solution quite a lot. If it weren't for those, I'd have this 8-byte solution:

```
?+
;,;!@

```

# Answer
> 2 votes
# Perl 5 `-MList::Util=sum -pF/\D+/`, 8 bytes

```
$_=sum@F

```

Try it online!

# Answer
> 2 votes
# 05AB1E (legacy), 5 bytes

```
.œþOà

```

Try it online or verify a few more test cases. (Times out for the larger test cases due to the  builtin.)

**Explanation:**

```
.œ     # Get all partitions of the (implicit) input-string,
       # which are all possible ways of dividing the input-strings into substrings
  þ    # Only leave the items consisting of digits for each partition
       # (in the new version of 05AB1E, an explicit `€` is required)
   O   # Sum each inner list
    à  # Pop and push its maximum
       # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Bash \+ GNU utilities, 24 bytes

```
dc<<<`tr -c 0-9 +<<<$s`p

```

Try it online!

Input in the variable `s`, output on `stdout`.

# Answer
> 2 votes
# Pip, 7 bytes

```
$+a@+XD

```

Try it online!

Regexes all numbers to a list and sums them.

+1 byte fix from DLosc.

# Answer
> 2 votes
# Vyxal `s`, 6 bytes

```
`\D`ṡ⌊

```

Try it Online!

~~Ugh we really need to make  play nice with strings not containing numbers in v2.6; this would be 6 bytes if it didn't error.~~ 2.6 done did make the change lol.

## Explained

```
`\D`ṡ⌊
`\D`   # The string "\D" (a regex that looks for non-digits)
    ṡ  # Split the input on this regex
     ⌊ # Convert each to a number
       # Output the sum with the `s` flag

```

# Answer
> 1 votes
## Perl, 16 chars

```
s/\d+/$r+=$&/ge;

```

Takes input in `$_`, output goes on `$r`. Last semicolon is superfluous, but it will probably be needed when the program does more things. Add `say$r` for output.

# Answer
> 1 votes
# PHP - 37

Without printing;

```
<?array_sum(@split("[^0-9]+",`cat`));

```

With printing (38):

```
<?=array_sum(@split("[^0-9]+",`cat`));

```

# Answer
> 1 votes
## R, 30

```
sum(scan(t=gsub("\\D"," ",x)))

```

Here, `x` is the name of the variable.

Example:

```
> x  <- "e7rde f ,fe 43 jfj 54f4sD"
> sum(scan(t=gsub("\\D"," ",x)))
Read 4 items
[1] 108

```

# Answer
> 1 votes
# J - 23 char

Not a winner, but we get to see a fairly rare primitive in action.

```
+/".(,_=_"."0 y)}y,:' '

```

Explained:

* `_"."0 y` \- For each character in the input string `y`, try to read it in as a number. If you can't, use the default value `_` (infinity) instead.
* `,_=` \- Check each result for equality to `_`, and then run the final array of 0s and 1s into a vector. (`"."0` always adds one too many dimensions to the result, so we correct for that here.)
* `y,:' '` \- Add a row of spaces beneath the input string.
* `}` \- Used as it is here, `}` is called *Item Amend*, and it uses the list of 0s and 1s on the left as indices to select the row to draw from in the right argument. So what happens is, for each column in the right side, we take the original character if it could be read in as a number, and otherwise we take the space beneath it. Hence, we cover up any non-numeric characters with spaces.
* `+/".` \- Now convert this entire string into an list of numbers, and sum them.

# Answer
> 1 votes
# C 96

**Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**

```
t;main(i,v)int**v;{for(char*q,*s=v[1];*s;q>s?t+=abs(i),s=q:s++)i=strtol(s,&q,0);printf("%d",t);}

```

Try it online!

An earlier 85 byte version that is cheating a bit by hardcoding the string inside the program:

```
t=0;main(i){for(char*q,*s;i=strtol(s,&q,0),*s;q>s?t+=abs(i),s=q:s++);printf("%d",t);}

```

To actually use the 85 byte program you need to assign the variable like so:

```
t=0;main(i){for(char*q,*s="text";i=strtol(s,&q,0),*s;q>s?t+=abs(i),s=q:s++);printf("%d",t);}

```

# Answer
> 1 votes
## Actually, 14 bytes

```
9u▀8╙r♂┌-@s♂≈Σ

```

Try it online!

This program supports the CP437 code page for input.

Explanation:

```
9u▀8╙r♂┌-@s♂≈Σ
9u▀             base 10 digits (0-9)
   8╙r♂┌        all characters in CP437 (map(ord_cp437, range(2**8)))
        -       set difference
         @s     split input on any value in the resulting list
           ♂≈Σ  convert to ints and sum

```

# Answer
> 1 votes
# Brachylog, 9 bytes

```
{~cịˢ+}ᶠ⌉

```

Try it online!

It's... inefficient... so I've neglected to test the longer cases. It appears to work, though. Takes input through the input variable, which just so happens to be the usual form of input anyhow.

```
        ⌉    The output is the largest
{     }ᶠ     possible
     +       sum of
   ịˢ        integers the string representations of which are some elements of
 ~c          a partition of the input.

```

ensures that numbers are maximally matched as well as never negative, since splitting a number up, invalidating a number, or turning it negative will never result in a larger sum.

# Answer
> 1 votes
# K4, ~~21~~ 14 bytes

**Solution:**

```
+/. .Q.n .Q.n?

```

**Explanation:**

With thanks to @cillianreilly - I didn't expect a string of numbers to be tokenised with `value`.

```
+/. .Q.n .Q.n? / the solution
         .Q.n? / lookup right in the string "0123456789"
    .Q.n       / index back into "0123456789"
  .            / 'value', tokenises string into integers
+/             / sum up

```

# Answer
> 1 votes
# Stax, 8 bytes

```
µÖ▀o)♫⌐ƒ

```

Run and debug it

Finds all substrings matching `\d+`, then `eval` and sum.

# Answer
> 1 votes
# Funky, 38 bytes

```
s=>{n=0forv ins::gmatch"\\d+"n-=-v[0]}

```

## Explained

```
s=>{                                 } $# A function taking argument "s"
    n=0                                $# Preset n to 0
              s::gmatch"\\d+"          $# An iterator function which finds all groups of digits in a string
       forv in                         $# Iterate through, setting v to the match
                             n-=       $# Subtract n by
                                -v[0]  $# The negative of the whole match, which implicitely numberfies it.
                                       $# Conveniently implcit return from last statement in the function.

```

Try it online!

# Answer
> 1 votes
# Japt v2.0a0 `-x`, 3 bytes

```
q\D

```

Try it

# Answer
> 1 votes
# Husk, 4 bytes

```
ṁiġ√

```

Try it online!

# Explanation

```
ṁiġ√
  ġ√ group on isalpha
ṁ    sum
 i   the first integer in each string

```

# Answer
> 1 votes
# Ruby `-n`, 26 bytes

```
p eval"#$_ 0".gsub /\D/,?+

```

Attempt This Online!

Appends  `0` to the input, replaces each non-digit with `+`, then evals.

# Answer
> 1 votes
# Retina 0.8.2, 12 bytes

```
S`\D
.+
$*
.

```

Try it online.

**Explanation:**

Split on non-digit characters, putting each number on its own separated line:

```
S`\D

```

Convert each number to unary, and implicitly remove the newlines:

```
.+
$*

```

Convert it from unary back to an integer, which is output implicitly as result:

```
.

```

# Answer
> 0 votes
# Smalltalk (Smalltalk/X) (51 chars)

using the regex pakage:

```
(s regex:'\d+' matchesCollect:[:n|n asNumber])sum

```

w.o. regex:

```
((s asCollectionOfSubCollectionsSeparatedByAnyForWhich:[:c|c isDigit not]) map:#asNumber)sum

```

input in s

# Answer
> 0 votes
## Javascript - 43 chars

I know it's long, but there was no JS solution so :)

```
c=0
a=a.split(/[^\d]/g)
for(i in a)c+=+a[i]

```

`a`is the string. `c` contains answer.

# Answer
> 0 votes
## Tcl, 30

```
expr [regsub -all \\D+ $a.0 +]

```

It assumes that the input is in the variable `$a` (formally, in `a`) and stores the answer in the interpreter result. I/O is left as an exercise.

# Answer
> 0 votes
## APL, 16 bytes

```
{+/⍎b\⍵/⍨b←⍵∊⎕d}

```

`⎕d` is a built-in containing the digits (0-9). `b` is assigned to a vector of 0/1 where 1 is given to the characters that are digits. `b` is used to compress the given character array and then reused to expand it, which inserts blanks.  is APL's *eval* which converts a string into a vector a integers, in this case. `+/` computes the sum.

# Answer
> 0 votes
# Swift 3, 78

```
s.characters.split{!("0"..."9"~=$0)}.flatMap{Int(String($0))}.reduce(0){$0+$1}

```

where `s` is the string

# Answer
> 0 votes
# Perl - 24 chars

```
warn eval join'+',/\d+/g

```

Input is in $\_

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 76 bytes

```
	I =INPUT
S	I SPAN(&DIGITS) . X REM . I	:F(O)
	O =O + X	:(S)
O	OUTPUT =O
END

```

Try it online!

# Answer
> 0 votes
# Arturo, 29 bytes

```
$=>[match&{/\d+}do~"∑|<=|"]

```

Try it

```
$=>[             ; a function
    match&{/\d+} ; get the numbers in the input as a block of strings; push to stack
    do           ; eval
    ~            ; interpolate
    "∑|<=|"      ; sum TOS
]                ; end function

```

# Answer
> 0 votes
# Thunno, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
"\d+"AfiS

```

Attempt This Online! or verify all test cases

#### Explanation

```
"\d+"AfiS  # Implicit input
"\d+"Af    # Regex findall "\d+"
       i   # Convert to integers
        S  # Sum

```

---
Tags: code-golf, string
---