title: Am I a Self Number?

text:
# Question
Title: Am I a Self Number?
A self number (also called a Colombian or Devlali number) is a natural number, `x`, where the equation `n + <digit sum of n> = x` has no solutions for any natural number `n`. For example, **21** is not a self number, as `n = 15` results in `15 + 1 + 5 = 21`. On the other hand, **20** *is* a self number, as no `n` can be found which satisfies such an equality.

As this definition references the digit sum, it is base dependent. For the purposes of this challenge, we will only be considering base 10 self numbers, which are sequence A003052 in the OEIS. Binary (A010061) and base 100 (A283002) self numbers have also been calalogued.

## The Challenge

Given a positive integer `x` as input, output a truthy value if `x` is a self number in base 10, and a falsey value otherwise. For clarification of truthy and falsey values, refer to this meta post on the subject.

You may write a full program or function, and input and output may be provided on any of the usual channels. Standard loopholes are, of course, banned.

This is , so the shorter your answer (in bytes) the better!

## Test cases

Truthy:

```
1
3
5
7
9
20
31
86
154
525

```

Falsey:

```
2
4
6
8
10
15
21
50
100
500

```

Sandbox link

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=159881,OVERRIDE_USER=41020;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Octave, 37 bytes

```
@(n)sum(dec2base(t=1:n,10)'-48,1)+t-n

```

Port of my MATL answer.

Try it online!
> 9 votes

# Answer
# Java (JDK 10), 84 bytes

```
i->{for(int n=i;i-->1;)i|=((""+i).chars().map(x->x-48).sum()+i^n)-1>>-1;return~i<0;}

```

Try it online!

## Explanation

```
i->{                                    // IntPredicate
  for(int n=i;i-->1;)                   //  for each number below n
    i|=(                                //   keep the sign of
      (""+i).chars().map(x->x-48).sum() //    sum of digits
      +i                                //    plus the number
      ^n                                //    xor n (hoping for a zero)
     )-1>>-1;                           //    changing that into a negative number if equals to zero
  return~i<0;                           //  return i>=0
}

```

## Credits
> 7 votes

# Answer
# 05AB1E, 8 bytes

```
LD€SO+ÊW

```

Try it online! or as a Test suite

**Explanation**

```
L          # push range [1 ... input]
 D         # duplicate
  €S       # split each number into a list of digits
    O      # sum digit lists
     +     # add (n + digitSum(n))
      Ê    # check for inequality with input
       W   # min

```
> 6 votes

# Answer
# Brachylog, 12 bytes

```
¬{⟦∋Iẹ+;I+?}

```

Try it online!

### Explanation

```
¬{         }    Fails if succeeds, suceeds if fails:
  ⟦∋I             I ∈ [0, ..., Input]
    Iẹ+           The sum of the elements (i.e. digits) of I...
       ;I+?       ... with I itself results in the Input

```
> 6 votes

# Answer
# Octave, ~~49~~ ~~47~~ 44 bytes

```
@(x)arrayfun(@(k)k+sum(num2str(k)-48)-x,1:x)

```

Try it online!

**Explanation:**

Trying to do the operation on a range is cumbersome and long, since `num2str` returns a string with spaces as separators if there are more than input number. Subtracting 48 would therefore give something like: `1 -16 -16 2 -16 -16 3 -16 -16 4` for an input range **1 ... 4**. Getting rid of all the `-16` takes a lot of bytes.

Therefore, we'll do this with a loop using `arrayfun`. For each of the numbers **k = 1 .. x**, where **x** is the input, we add `k` and its digit sum, and subtract `x`. This will return an array of with the result of that operation for each of the numbers in **k**. If any of the numbers in the array is a zero, the number is not a self number.

For inputs `20` and `21`, the outputs are:

```
20:  -18, -16, -14, -12, -10, -8, -6, -4, -2, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9, 2
21:  -19, -17, -15, -13, -11, -9, -7, -5, -3, -10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 1, 3

```

There are only non-zero elements for input `20`, and at least one non-zero element for input `21`. That means that `20` is a self number, and `21` is not.

Octave treats an array with at least one zero as false, as can be seen in the TIO-link.
> 5 votes

# Answer
# C (gcc), ~~70~~ ~~67~~ 65 bytes

```
i,r,d,j;f(n){for(r=i=n;d=j=--i;r*=d!=n)for(;j;j/=10)d+=j%10;i=r;}

```

Try it online!

To shave off another 2 bytes, the truthy value returned is no longer 1, but the number itself.
> 5 votes

# Answer
# , 28, 24, 22 21 bytes

-1 byte thanks to Conor O'Brien

-2 byts thanks to ngn

```
$@-.(+1#.,.&.":)"+@i.

```

Try it online!

## Explanation:

`i.` a list 0 .. n-1

`( )"+` for each item in the list

`.,.&.":` convert it to a list of digits,

`1#` find their sum

`+` and add it to the item

`$@-.` exclude the list from the argument and find the shape
> 5 votes

# Answer
# MATL, 11 bytes

```
t:tFYA!Xs+-

```

The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy if it contains one or more zeros.

Try it online! Or verify all test cases, including truthiness/falsihood test.

### Explanation

Consider input `n = 10` as an example.

```
t       % Implicit input, n. Duplicate
        % STACK: 10, 10
:       % Range
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10]
t       % Duplicate
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 10]
FYA!    % Convert to base 10 digits and transpose
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [0 0 0 0 0 0 0 0 0 1
                                              1 2 3 4 5 6 7 8 9 0]
Xs      % Sum of each column
        % STACK: 10, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 1]
+       % Add, element-wise
        % STACK: 10, [2 4 6 8 10 12 14 16 18 11]
-       % Subtract, element-wise
        % STACK: [8 6 4 2 0 -2 -4 -6 -8 -1]
        % Implicit display

```
> 4 votes

# Answer
# Pari/GP, 32 bytes

```
n->!sum(i=1,n,i+sumdigits(i)==n)

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog), 14 bytes

```
~⊢∊⍳+(+/⍎¨∘⍕)¨∘⍳

```

Try it online!

**How?**

```
               ⍳   range
     (  ⍎¨∘⍕)      digits
     (+/    )      digit sums
   ⍳+              vectorized addition with the range
 ⊢∊                is the input included?
~                  negate

```
> 3 votes

# Answer
# Jelly, 6 bytes

```
ḟDS+Ɗ€

```

For input **n**, this returns **\[n\]** if **n** is a self number, **\[\]** if not.

Try it online!

### How it works

```
ḟDS+Ɗ€  Main link. Argument: n

     €  Call the link to the left for each k in [1, ..., n].
    Ɗ     Drei; combine the three links to the left into a monadic chain.
 D          Decimal; map k to the array of its digits in base 10.
  S         Take the sum.
   +        Add k to the sum of the k's digits.
ḟ       Filterfalse; promote n to [n], then remove all elements that appear in the
        array to the right.
        This returns [n] if the array doesn't contain n, [] if it does.

```
> 3 votes

# Answer
# Haskell, 46 bytes

```
f x=and[x/=n+sum[read[d]|d<-show n]|n<-[1..x]]

```

Try it online!
> 3 votes

# Answer
# Scala, ~~44~~ 42 bytes

```
x=>0 to x forall(n=>x!=(n/:s"$n")(_+_-48))

```

Try it online
> 3 votes

# Answer
# Python 3, 60, 56, 55, 54 bytes

```
lambda x:{x}-{n+sum(map(int,str(n)))for n in range(x)}

```

Try it online!

-4 using all inverse instead of any
-1 by changing != to ^ by @jonathan-allan
-1 by using sets by @ovs
> 2 votes

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

```
{!grep $_,map {$_+[+] .comb},^$_}

```

Try it out!

A bare block with implicit single parameter, called thus:

```
say {!grep $_,map {$_+[+] .comb},^$_}(500);
> False
say {!grep $_,map {$_+[+] .comb},^$_}(525);
> True

```

Since `n + digits(n) >= n`, we can just calculate the Colombian number for all the numbers up to our query value and see if any of them match. So this calculates the Colombian number for a given input:

```
{$_ + [+] .comb}

```

Which we apply to all the values up to our target:

```
(^$_).map({$_+[+] .comb})

```

But we only care whether any of them match, not what those values are, so as pointed out by @nwellenhof, we can grep:

```
grep $_, map {$_+[+] .comb}, ^$_

```

The rest is just coercion to bool and wrapping in a block.

## 39 bytes

```
{!((^$_).map({$_+[+] .comb}).any==$_)}

```

TIO test link provided by @Emigna

@nwellenhof pointed out that using grep would save 6 bytes!
> 2 votes

# Answer
# Perl 5 `-a`, 34 bytes

```
#!/usr/bin/perl -a
say!grep{s/./$_+=$&/reg;/@F/}1..$_

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~70~~ 66 Bytes

```
lambda x:[i for i in range(x)if i+sum([int(j)for j in`i`])==x]==[]

```

EDIT: -4 thanks to @user56656
> 2 votes

# Answer
# Ruby, 38 bytes

```
->x{(1..x).all?{|n|n+n.digits.sum!=x}}

```

Try it online!
> 2 votes

# Answer
# Pyth, 8 bytes

```
!/m+sjdT

```

Test suite.

If swapping truthy / falsy values is allowed, then we can drop the `!` and get 7 bytes instead. One of Sok's suggestions helped me golf 2 bytes.

## Explanation

```
!/m+sjdT – Full program. Takes an input Q from STDIN, outputs either True or False.
  m      – Map over the range [0 ... Q) with a variable d.
     jdT – Convert d to base 10.
    s    – Sum.
   +     – And add the sum to d itself.
 /       – Count the occurrences of Q in the result.
!        – Negate. Implicitly output the result.

```
> 2 votes

# Answer
# Japt `-d!`, 6 bytes

```
N¥U+ìx

```

Try it

---

## Original, 8 bytes

Returns the input number for truthy or `0` for falsey. If only the empty array were falsey in JavaScript, this could be 7 bytes.

```
ÂNkUÇ+ìx

```

Try it

---

### Explanation

```
             :Implicit input of integer U
   UÇ        :Generate the range [0,U) and pass each Z through a function
      ì      :  Digits of Z
       x     :  Reduce by addition
     +       :  Add to Z
  k          :Remove the elements in that array
 N           :From the array of inputs
Â            :Bitwise NOT NOT (~~), casts an empty array to 0 or a single element array to an integer

```

---

### Alternative

```
Ç+ìxÃe¦U

```

Try it

```
             :Implicit input of integer U
Ç            :Generate the range [0,U) and pass each Z through a function
  ì          :  Digits of Z
   x         :  Reduce by addition
 +           :  Add to Z
    Ã        :End function
     e       :Every
      ¦U     :  Does not equal U

```
> 2 votes

# Answer
# Add++, ~~27~~ 18 bytes

```
L,RFBDB+B]ARz€b+Ae

```

Try it online!
> 2 votes

# Answer
# , 20 bytes

```
#@-.i.+1#.10#.inv i.

```

Try it online!

```
                  i.     Range [0,n-1]
          10#.inv        To base 10
       1#.               Sum the digits
    i.+                  Plus the corresponding number
  -.                     Remove from the input, leaves an empty list if it was a self number.
#@                       An empty list is truthy, so return the length instead.

```
> 2 votes

# Answer
# Perl 5 `-apl -MList::Util=sum,all`, 28 bytes

```
$_=all{"@F"-sum/./g,$_}1..$_

```

Try it online!
> 2 votes

# Answer
# Pip, ~~18~~ 12 bytes

```
aNI:_+$+_M,a

```

Attempt This Online!

*-6 thanks to @DLosc*

#### Explanation

```
aNI:_+$+_M,a  ; Full program. Input (a) on command line
         M,a  ; Map over the range from 0 to a (_)
      $+_     ;  Sum _
    _+        ;  And add this to _
aNI:          ; Is a not in this list?
              ; Implicit output

```

Old:

```
$*Y{\a!=a+$+a}M\,a  ; Full program. Input (n) on command line.
               \,a  ; Range from 1 to n
   {         }M     ; Map over this list (a):
          $+a       ;  Sum the digits of a
        a+          ;  Add to a
    \a!=            ;  And check if it's not equal to n
$*Y                 ; Get the product of this list
                    ; Implicit output

```
> 2 votes

# Answer
# Lua, 81 bytes

```
for i=1,...do a=i+0(i..''):gsub('.',load'a=a+...')b=b or a==0+...end print(not b)

```

Try it online!

```
for i=1,...do
    a=i+0                            -- +0 is needed to avoid an error
    (i..''):gsub('.',load'a=a+...')  -- Sums up all the digits of i
    b=b or a==0+...                  -- Sets b to true if a equals the input
end
print(not b)

```
> 2 votes

# Answer
# Arturo, ~~36~~ 34 bytes

```
$->x[every? x'n->x<>+∑digits<=n]

```

Try it
> 2 votes

# Answer
# FunStack alpha, 46 bytes

```
All? Minus Plus foldl ToBase 10 hook map From0

```

Try it at Replit!

### Explanation

First, we construct a function that adds a number to its base-10 digit sum:

```
Plus foldl                 Left-fold second argument on addition, with first
                           argument as starting value
                     hook  Take a single argument; pass it to the above function
                           twice: first, unchanged, and second, passed through
                           the following function:
           ToBase 10       Convert to list of base-10 digits

```

This is a bit shorter than the alternatives:

```
Plus Sum ToBase 10 over hook
Sum Pair ToBase 10 compose3

```

Then:

```
                   From0  Range of integers from 0 up to input-1
           ... map        Map the above function to each
     Minus                Subtract each from the input
All?                      Are all results truthy (non-zero)?

```
> 2 votes

# Answer
# JavaScript (ES6), ~~52~~ 51 bytes

*Saved 1 byte thanks to @l4m2*

Returns **0** or **1**.

```
n=>(g=k=>k?eval([...k+'k'].join`+`)-n&&g(k-1):1)(n)

```

Try it online!
> 1 votes

# Answer
# Retina, 55 bytes

```
.+
*
Lv`_+
_+
$&$.&
^_+
$&¶$&
\d
*
Cms`^(_+)\b.*¶\1\b
0

```

Try it online! Link includes test cases. Explanation:

```
.+
*

```

Convert input `x` to unary.

```
Lv`_+

```

Create a range from `x` down to `1`.

```
_+
$&$.&

```

Suffix the decimal value of each `n` to its unary value.

```
^_+
$&¶$&

```

Make a copy of `x`.

```
\d
*

```

Convert each decimal digit of `n` to unary, thus adding the digits to the existing copy of `n`.

```
Cms`^(_+)\b.*¶\1\b

```

Check whether `x` appears in any of the results.

```
0

```

Invert the result.
> 1 votes

# Answer
# Haskell, ~~63~~ 58 bytes

```
s 0=0
s x=x`mod`10+s(x`div`10)
f n=all(\x->x+s x/=n)[1..n]

```

Try it online!
> 1 votes

# Answer
# Attache, ~~31~~ 20 bytes

```
${0={Sum@_+_=x}~1:x}

```

Try it online!

`{Sum@_+_=x}` performs the check, `~1:x` counts how many occurrences of that check are in the range from `1` to `x`, and `0=` asserts that there are no such elements.

---

## Attache, 30 bytes

```
None##`=#{_+Sum=>Digits!_}@1&`:

```

Try it online!

## Explanation

This is a composition (`##`) of two functions:

* `None`
* ``=#{_+Sum=>Digits!_}@1&`:`

This means that whatever the second function returns, `None` will ensure it contains no truthy values

The second function is a fork (`#`) of two functions:

* ``=`
* `{_+Sum=>Digits!_}@1&`:`

This means that, given an input `n`, this fork checks for equality with `n` and each member of this second function.

This second function is also a composition (`@`) of two functions, being `{_+Sum=>Digits!_}`, which sums the digits of the input and adds it to the input and applies this function to each member of the range from 1 to `n` (`1&`:`).

In summary, this checks that no (`None`) element added to its digits (`{_+Sum=>Digits!_}`) from 1 to `n` (`1&`:`) is equal to (``=`) `n`.
> 1 votes

# Answer
## Retina, 24 bytes

```
.+
*

$.`¶$`
\d
*
D`
.\z

```

Try it online!

Could be 18 bytes with input given in unary, but the other Retina answer uses decimal as well, so I figured using decimal would make for a fairer comparison.

### Explanation

```
.+
*

```

Convert input to unary, using `_` as the unary digit.

```

$.`¶$`

```

At each position in the string (i.e. beginning, end, and between every pair of characters), insert: `$.``, the length of the prefix (or the zero-indexed position of the match), , a linefeed, `$``, the prefix itself (i.e. a unary representation of the zero-indexed position). E.g. if the input was `3` and we'd have the unary representation `___`, then this would result in:

```
0
_1
__2
___3
___

```

In other words, we get one line for each number from 0 to the input (inclusive), which holds both a unary and a decimal representation of that number.

```
\d
*

```

We convert each digit to unary, which effectively computes the digit sum on each line and adds it to the number itself (all in unary).

```
D`

```

Deduplicate lines. This doesn't actually delete duplicate lines but just clears them to empty lines. So if any number from 0 to the input plus its digit sum is equal to the input, the last line will get cleared. Otherwise, the last line remains in place.

```
.\z

```

Check whether there's still a character on the last line. We can't use `$`, because that also matches in front of a trailing linefeed (which is exactly where we don't want to look).
> 1 votes

# Answer
## Bash + GNU Coreutils, 91 Bytes

Returns truthy or falsy.

```
e=1;for((i=1;i<=$1;i++));{ [ $(bc<<<`grep -o . <<<$i|tr '\n' +`$i) -eq $1 ]&&e=0; };exit $e

```
> 1 votes

# Answer
# Kotlin, 48 bytes

```
x->(1..x).all{v->"$v".sumBy{it.toInt()-48}+v!=x}

```

Try it online!

Explanation:

```
(1..x)      // Range of numbers from 1 to x
.all{v->    // Function expression that checks if ALL values evaluate to tru
"$v"        // Convert the value into a string
.sumBy{it.toInt()-48} // For each character, get the ASCII char value, subtract 48 in order to get it back to the numerical value, and then sum it up
+v          // Add the original number
!=x}        // Ensure that it does not equal the input

```
> 1 votes

# Answer
# Elixir, ~~66~~ 65 bytes

```
fn a->!Enum.any?1..a,fn b->a==b+Enum.sum Integer.digits b end end

```

Try it online!
> 1 votes

# Answer
# Stax, 8 bytes

```
Å8avj╒Éπ

```

Run and debug it

## Explanation

ASCII equivalent:

```
{cE+|+x=f!
{       f     Filter [1..input] with block
 cE           Decimal digits of current value
   +|+        Sum of digits and the current value
      x=      Equals input
         !    Logical not, maps empty array to 1 and non-empty array to 0

```

`fcE+|+x=` is a Stax program that outputs all numbers whose sum of digits added to itself equals the input. For example for `101` the output would be `91` and `100`, each on a separate line.

Run and debug it
> 1 votes

# Answer
# Pyt, 7 bytes

```
ĐřĐŚ+∈¬

```

Try it online!

If swapping truthy/falsy values is allowed, then the `¬` at the end can be dropped for 6 bytes.

Explanation:

```
        Implicit input
Đ       Duplicate input
ř       Get [1,2,...,input]
Đ       Duplicate the top of the stack
Ś       Get the sum of the digits of each element in the array
+       Add the top two items on the stack element-wise
∈       Is the input in the list?
¬       Negate the top of the stack
        Implicit print

```
> 1 votes

# Answer
# Io, 81 bytes

Io doesn't allow `split("")` or list-based base conversion. Therefore I need to do a terrible chain of type conversions...

```
method(n,Range 1 to(n)map(i,i+i asString asList map(asNumber)sum)indexOf(n)==nil)

```

Try it online!
> 1 votes

# Answer
# Vyxal, 6 bytes

```
ƛ∑+;c¬

```

Try it Online!

Just another 6 byter. Kinda sorta ports Jelly in that it maps `sum(digits) + n` to the range 1..input. 5 bytes if inverted booleans are allowed.

## Explained

```
ƛ∑+;c¬
ƛ  ;   # To each number N in the range [1, input]
 ∑     #  sum the digits of N
  +    #  and add that to N
    c  # is the input in that?
     ¬ # logical not of that

```
> 1 votes

# Answer
# Desmos, 59 bytes

```
f(k)=∏_{n=1}^ksgn(n+∑_{a=0}^nmod(floor(n/10^a),10)-k)^2

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Nibbles, ~~5.5~~ 5 bytes (10 nibbles)

```
-_.,$++`@~

```

Attempt This Online!

Outputs self-numbers unchanged (truthy), or an empty list (falsy) for non-self-numbers.

```
-_.,$++`@~      # program;
-_.,$++`@~$$    # program with implicit variables;
  .             # map over each x in
   ,$           # 1..input:
     +          #   add:
      +         #     sum of
       `@ $     #       digits of x in base
         ~      #       10
                #   to
           $    #     x
-               # now remove any of these items from
 _              # input treated as a list

```

Note that if reversed truthy/falsy was permitted\*, the previous 5.5-byte version (`-~?.,$++`@~`) could have been reduced to only 4.5-bytes (`?.,$++`@~`).
> 1 votes

# Answer
# Julia 1.0, 36 bytes

```
~x=all(1:x.|>n->n+sum(digits(n))!=x)

```

Try it online!

-1 byte thanks to MarcMush: rewrite to use `all` instead of `!any`
> 1 votes

# Answer
# Thunno 2 `!`, 5 bytes

```
æDS+=

```

Try it online! or verify all test cases

#### Explanation

```
æDS+=  # Implicit input
æ      # Filter [1..input] by:
  S+   #  Add the digit sum
 D     #  To itself
    =  #  Does this equal the input?
       # Take the logical NOT
       # Implicit output

```
> 0 votes

# Answer
# ARBLE, 51 bytes

```
nt(sum(range(1,n)|eq(x+sum(explode(""..x,".")),n)))

```

Try it online!
> 0 votes

# Answer
# PowerShell, ~~80~~ 73 bytes

```
$args|%{$a=@();1..($_-1)|%{$a+=$_+(("$_"|% t*y)-join"+"|iex)};$_-notin$a}

```

Try it online!

**Explanation**

```
$args | % {
 $a=@()      # creates an empty array
 1..($_-1)   # loops through 1 to n-1
 | % { $a += $_ + ( ("$_" | % t*y) -join "+" | iex )}

 # adds 'currentNum + turns num into array and joins by "+" then invokes
 # expression' to the array

 $_-notin$a  # checks if n is in the array
}

```

-7 by changing `-notcontains` to `-notin` and `param($x)` to `$args`
> 0 votes

---
Tags: code-golf, math, decision-problem
---


title: Compressed UTF-8

text:
# Question
Title: Compressed UTF-8
In the UTF-8 encoding bytes of the Form `10******` can only appear within multi-byte sequences, with the length of the sequence already being determined by the first byte. When UTF-8 text is split within a multi-byte UTF-8 character sequence, this prevents that the second part of the sequence is wrongly detected as another character. While in for normal Text files this error-checking is a good idea (and prevents unwanted ASCII control characters/null-bytes from appearing in the byte-stream), for code-golf this redundancy is just wasting bits.

Your task is to write **two** programs or functions, one decoder and one encoder converting between code-points and "compressed UTF-8", defined the following way:

```
1 byte sequence:
bytes 0x00 to 0xbf  -> code-points 0x00 -> 0xbf

2 byte sequence  (code-points 0x00 -> 0x1fff):
0b110AAAAA 0bBBCCCCCC
-> code-point 0b (BB^0b10) AAAAA CCCCCC

3 byte sequence (code-points 0x00 -> 0xfffff):
0b1110AAAA 0bBBCCCCCC 0bDDEEEEEE
-> code-point 0b (BB^10) (DD^10) AAAA CCCCCC EEEEEE

4 byte sequence (code-points 0x00 -> 0x7ffffff):
0b11110AAA 0bBBCCCCCC 0bDDEEEEEE 0bFFGGGGGG
-> code-point 0b (BB^10) (DD^10) (FF^10) AAA CCCCCC EEEEEE GGGGGG

```

Or in short form: The compressed UTF-8 code-point for a sequence of bytes, is the regular UTF-8 code-point for that byte-sequence, with the difference of the high two bits and `0b10` prepended on the start of the number.

Examples:

```
decode:
[] -> []
[0xf0, 0x80, 0x80, 0x80] -> [0x00]
[0x54, 0x65, 0x73, 0x74] -> [0x54, 0x65, 0x73, 0x74]
[0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0xc2, 0xbb, 0xc2, 0xb5, 0xc2, 0xba, 0xc2, 0xa9, 0xc2, 0xbf, 0xc2, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0xe2, 0x84, 0x95, 0xc3, 0x97, 0xe2, 0x84, 0x95] -> [0x2115, 0xd7, 0x2115]
[0xf0, 0x9f, 0x8d, 0x8f, 0xf0, 0x9f, 0x92, 0xbb] -> [0x1f34f, 0x1f4bb]
[0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb]             -> [0x1f34f, 0x1f4bb]

encode:
[] -> []
[0x54, 0x65, 0x73, 0x74] -> [0x54, 0x65, 0x73, 0x74]
[0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab] -> [0xbb, 0xb5, 0xba, 0xa9, 0xbf, 0xab]
[0x2115, 0xd7, 0x2115] -> [0xe2, 0x84, 0x95, 0xc3, 0x97, 0xe2, 0x84, 0x95]
[0x1f34f, 0x1f4bb] -> [0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb]
// [0x1f34f, 0x1f4bb]=[0b1_1111_001101_001111,0b1_1111_010010_111011]
// [0xef, 0x8d, 0xcf, 0xef, 0x92, 0xfb]=[0b11101111,0b10001101,0b11001111,0b11101111,0b10010010,0b11111011]

```

## Rules

* You are allowed to use your languages internal string representation instead of code-point arrays for input/output
* When encoding a code-point you should return the shortest sequence representing that code-point
* The input may contain multiple code-points / bytes representing multiple code-points
* You only need to handle code-points in the range (0x00 to 0x10ffff)
* You score will be the sum of the lengths of the two programs
* This is the shortest solution wins

# Answer
# JavaScript (ES10), 228 bytes

This code is solely based on bitwise operations. There may be a better way with some built-ins. At any rate, I can't say I'm very happy with it.

## Decoder (105 bytes)

```
a=>a.flatMap(i=v=>i--?(n=n<<6|v&63|(v&192^128)<<5*s-4*i,i?[]:n):(s=i=(v>>4)**4>>14)?(n=v&~0>>>26+s,[]):v)

```

Try it online!

A somewhat interesting formula in there is `(v >> 4) ** 4 >> 14` which turns the leading byte \\$v\\$ into the number of extra bytes in the sequence.

| v \>\> 4 | (v \>\> 4) \** 4 | (v \>\> 4) \** 4 \>\> 14 |
| --- | --- | --- |
| 0b0000 (0x0) | 0b0000000000000000 | 0 |
| 0b0001 (0x1) | 0b0000000000000001 | 0 |
|  |  |  |
| 0b1011 (0xB) | 0b0011100100110001 | 0 |
| 0b1100 (0xC) | 0b0101000100000000 | 1 |
| 0b1101 (0xD) | 0b0110111110010001 | 1 |
| 0b1110 (0xE) | 0b1001011000010000 | 2 |
| 0b1111 (0xF) | 0b1100010111000001 | 3 |

## Encoder (123 bytes)

```
a=>a.flatMap(n=>n<192?n:(s=n>>13?n>>20?8:4:2,g=i=>i<s?[...g(i*2),n/i**6&63|n/s**5/i/i&192^128]:[n/s**6&63/s|384/s|192])(1))

```

Try it online!
> 4 votes

# Answer
# Perl 5, 570 bytes

```
sub{$_=join'',map sprintf('%08b',$_),@_;%c=qw(00 10 01 11 10 00 11 01);my@r;push@r,oct'0b'.(s/^110(.{5})(..)(.{6})// ? "$c{$2}$1$3":s/^1110(.{4})(..)(.{6})(..)(.{6})// ? "$c{2}$c{$4}$1$3$5":s/^11110(...)(..)(.{6})(..)(.{6})(..)(.{6})// ? "$c{$2}$c{$4}$c{$6}$1$3$5$7":s/.{8}//*$&) while y///c;@r},
sub{map 128^oct"0b$_",map{$_=sprintf"%032b",$c=$_;$c>0xfffff?do{/(..)(..)(..)(...)(.{6})(.{6})(.{6})$/;"01110$4",$1.$5,$2.$6,$3.$7}:$c>0x1fff?do{/(..)(..)(....)(.{6})(.{6})$/;"0110$3",$1.$4,$2.$5}:$c>0xbf?do{/(..)(.{5})(.{6})$/;"010$2",$1.$3}:do{/(.)(.{7})$/;(1-$1).$2}}@_}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 170 bytes

## Decoder, 81 bytes:

```
≔⮌ＡθＷθ«≔⊟θι¿‹ι¹⁹²⊞υι«≔⍘ι²η≔⌕η0ζ≔Ｅ⊖ζ⍘⁺⁶⁴⁰⊟θ²ε⊞υ⍘⁺⁺⭆ε✂κ²¦⁴¦¹✂η⊕ζχ¹⭆ε✂κ⁴χ¹¦²»»Ｅυ⍘ι¹⁶

```

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

```
≔⮌Ａθ

```

Reverse the input so that the bytes can be easily processed separately.

```
Ｗθ«

```

Repeat while there is still input to process.

```
≔⊟θι

```

Get the next byte.

```
¿‹ι¹⁹²⊞υι«

```

If this is a single byte code, then just push the code, otherwise:

```
≔⍘ι²η

```

Convert the first byte to binary.

```
≔⌕η0ζ

```

Get the total number of bytes in the sequence.

```
≔Ｅ⊖ζ⍘⁺⁶⁴⁰⊟θ²ε

```

Get the remaining bytes, add 640 to each, and convert them to base 2. This results in a string of the form `1XBBCCCCCC`.

```
⊞υ⍘⁺⁺⭆ε✂κ²¦⁴¦¹✂η⊕ζχ¹⭆ε✂κ⁴χ¹¦²

```

Extract the `B` and `C` portions of those bytes, sandwiching the `A` bits from the first byte in between, then convert the final string back from base `2`.

```
»»Ｅυ⍘ι¹⁶

```

Output everything in hex for convenience (decimal would save `4` bytes).

## Encoder, 89 bytes:

```
ＦＡ¿‹ι¹⁹²⊞υι«≔÷Ｌ↨ι²¦⁷θ≔⟦⟧ηＦθ«⊞η﹪ι⁶⁴≧÷⁶⁴ι»≔Ｘ²⁻⁶θθ⊞υ⁺﹪ιθ⁻²⁵⁶⊗θＦ⮌Ｅη⁺κ×⁶⁴﹪⁺²÷ι×θＸ⁴λ⁴⊞υκ»Ｅυ⍘ι¹⁶

```

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

```
ＦＡ

```

Loop over the input code points.

```
¿‹ι¹⁹²⊞υι«

```

If this is a single byte code point then just push the byte, otherwise:

```
≔÷Ｌ↨ι²¦⁷θ

```

Get the number of additional bytes.

```
≔⟦⟧ηＦθ«⊞η﹪ι⁶⁴≧÷⁶⁴ι»

```

Extract the bottom six bits of those bytes.

```
≔Ｘ²⁻⁶θθ⊞υ⁺﹪ιθ⁻²⁵⁶⊗θ

```

Push the first byte.

```
Ｆ⮌Ｅη⁺κ×⁶⁴﹪⁺²÷ι×θＸ⁴λ⁴⊞υκ

```

For each additional byte, extract its top two bits and push it.

```
»Ｅυ⍘ι¹⁶

```

Output everything in hex for convenience (decimal would save `4` bytes).
> 2 votes

---
Tags: code-golf
---


title: Hashers and Crashers (Cops)

text:
# Question
Title: Hashers and Crashers (Cops)
*This is the cops thread of this cops and robbers challenge. The robbers thread is here.*

Related, but hashes numbers instead of strings and uses a different scoring system.

## Definitions

A hash collision is when two different strings produce the same hash.

## Summary

In this challenge, the cops will make a hash function, with a collision they know of. Then, the robbers will try to crack it by finding a hash collision in the cop's hash algorithm. To crack an answer, the hash collision the robber finds does not have to be the intended solution.

If a cop submission is not cracked for 7 days, it is safe, so mark it as such and reveal the intended crack and the score.
If a cop submission is cracked, mark it as such and edit in a link to the crack.

## Rules

* Cryptographic functions are allowed only if you know a collision in them. If it is a famous and secure hash algorithm like SHA-256, you must post the hashes of each string in a different, specified hash algorithm (ideally also in a secure hash algorithm), like Keccak-512.

## Format

A cop answer has to **contain the language and the source code**.

## Scoring

The score of a safe cop answer is **the sum of the number of bytes of the two strings with the hash collision, with the *lower* score being better**.

## The winner

With robbers and cops being ranked separately, the winner is the person with the best scoring answer.

## Example

Cop:

> ### Python
>
> ```
> from hashlib import*
> def singlecharhash(x):
>   a = blake2b(digest_size=1)
>   a.update(x)
>   return a.hexdigest()
>
> ```

Robber:

> ### 4 Points, Cracks cop's answer
>
> `¯` and `É`, both 2 bytes.

## Pinboard

I am thinking of changing the scoring system to make it the minimum of the two strings. Any thoughts?

# Answer
# Python 3, Cracked

```
import hmac

def my_hash(x):
    assert type(x) == bytes
    return hmac.digest(x, b'good luck', 'sha256')

```

Function takes bytes. There are no typing/Python tricks here, it's a pure crypto challenge.
> 2 votes

---
Tags: cops-and-robbers, hashing
---


title: Speed of Lobsters

text:
# Question
Title: Speed of Lobsters
From the subreddit r/SpeedOfLobsters:

> Edit the text of an image to create a new phrase

This meme format/style is pretty self-explanatory. Simply have a browse through the subreddit if you need more examples. However, when coming up with ideas, it can be quite difficult to decide exactly which letters to keep and which to blank out to create my intended joke.

You are to take a sentence of space separated "words" (i.e. non-empty alphabetical strings) and a target "word" (still a non-empty alphabetical string) and "blank out" characters from the sentence in order to make the target word. For example:

```
"I do not control the speed at which lobsters die", "code" -> "*********co**************d***************e******"

```

Note that the order of the target word is maintained, so `**do*****c*********e****************************` is not an acceptable output. Earlier occurrences take priority, so `"testcase string", "tas"` should be `t****as********` not `t****a***s******`

You may input and output in any convenient method. You may use either uppercase or lowercase, so long as it is consistent across all inputs. You may use any character that will not appear in the input (i.e any non-alphabetic character, or characters of the opposite case to the input) to "blank out" characters.

The target word is guaranteed to be fully contained in the sentence (so `"abcdef", "xyz"` will never be an input) and will always be shorter than the sentence. The sentence will contain a minimum of two words (and therefore one space), each of which will be a minimum of 1 character long.

This is so the shortest code in bytes wins.

## Test cases

```
sentence
target
output

I do not control the speed at which lobsters die
code
*********co**************d***************e******

testcase string
tas
t****as********

uglhwagp qvyntzmf
ulhwagpqvyntzmf
u*lhwagp*qvyntzmf

qrkacxx wwfja jsyjdffa vwfgxf
qcfvf
q***c*****f************v*f***

z wzsgovhh jopw igcx muxj xmmisxdn t lmb
gcujxlb
*****g************c***u*j*x**********l*b

kxf jgmzejypb ya
e
********e*******

fe oxyk y
ex
*e**x****

o wr fmik
owrfmik
o*wr*fmik

pgezt yozcyqq drxt gcvaj hx l ix xemimmox
e
**e**************************************

kqclk b hkgtrh
k
k*************

sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw
crwqqhxl
******cr*********w*******q**q**h*x*l***************

teatsase
tas
t*a*s***

```

Thanks to Lyxal for helping me adapt the original idea of this into this version

# Answer
> 31 votes
# convey, 59 47 bytes

```
{
?;\,&:1<
v^<^ ,<$1
"=>^}"@"}
>">>#="
'*'>:<=0

```

Try it online! Run with `tas` and `tsase` (output is `t*as*`):

Split the input into two streams `?;\… ^<`, then always take one letter `:1`, compare it with the head `=`, and either `@` put the letter back into the queue `,` and output a `'*'$…}`, or output the letter `}` and take the next letter `$1`. After the queue is empty, to output the rest of the string, we push some dummy 1 values into the queue (by comparing the input with itself).

# Answer
> 16 votes
# JavaScript (ES6), 35 bytes

Expects `(haystack)(needle)`, where `haystack` is a list of characters and `needle` is either a list of characters or a string. Returns a list of characters. The blank-out character is `0`.

```
s=>w=>s.map(c=>c==w[s|=0]?++s&&c:0)

```

Try it online!

### Commented

```
s =>             // s[] = sentence as an array of characters
w =>             // w = word
s.map(c =>       // for each character c in s[]:
  c == w[s |= 0] //   we re-use s[] as a pointer into w; it's safe to
                 //   coerce it to a number with a bitwise OR because
                 //   s[] is guaranteed to contain only spaces and letters
  ?              //   if c is equal to w[s]:
    ++s && c     //     increment s and yield c
  :              //   else:
    0            //     yield the blank-out character "0"
)                // end of map()

```

# Answer
> 11 votes
# Haskell, ~~61~~ ~~59~~ 44 bytes

Saved ~~1~~ 16 bytes thanks to @ovs!

```
(a:b)%(c:d)|a==c=a:b%d
(_:b)%c='*':b%c
e%_=e

```

Try it online!

# Answer
> 11 votes
# x86-16 machine code, 11 bytes

Binary:

```
00000000: a674 054e 4fb0 2aaa e2f6 c3              .t.NO.*....

```

Listing:

```
        CHAR_LOOP:
A6          CMPSB               ; compare [DI] and [SI], advance both
74 05       JZ   MATCH          ; if same char, do nothing
4E          DEC  SI             ; back up target word to previous char
4F          DEC  DI             ; back up sentence to previous char
B0 2A       MOV  AL, '*'        ; load overstrike char
AA          STOSB               ; overwrite char with *, advance DI
        MATCH:
E2 F6       LOOP CHAR_LOOP      ; loop until end of sentence
C3          RET                 ; return to caller

```

Callable function, input sentence string at `[DI]`, length in `CX`, target word string at `[SI]`. Output is modified string at original `[DI]`.

Test using DOS DEBUG:

### Alternate version, 11 bytes

```
B0 2A       MOV  AL, '*'            ; load overstrike char
        CHAR_LOOP:
F3 A6       REPZ CMPSB              ; compare [DI++] and [SI++], repeat if same; CX--
4E          DEC  SI                 ; back up target word to previous char; DI--
4F          DEC  DI                 ; back up sentence to previous char; DI--
AA          STOSB                   ; overwrite char with *; DI++
41          INC  CX                 ; offset CX decrement from LOOP; CX++
E2 F8       LOOP CHAR_LOOP          ; loop until end of sentence
C3          RET                     ; return to caller

```

Saves 1 byte using `REPZ` instead of `JZ`, however it's lost because the loop needs to end when `CX` is `0` and unfortunately there's no `JCXNZ` instruction to do exactly that. Bummer.

# Answer
> 10 votes
# K (ngn/k), ~~24~~ 20 bytes

-4 bytes from using `" "` as the blank-out character

```
{y@<>y{y_x,y~:*x}/x}

```

Try it online!

Shoutout to @chrispsn and @ngn for helping to golf the above!

* `y{...}/x` set up a reduction seeded with `y` (the characters to search for), run over the characters in `x` (the full string). confusingly, within the function itself, `x` and `y` are flipped. this ends up returning a boolean array with `1`s in the positions containing the desired matches and `0`s everywhere else
* `y~:*x` compare the first character to search for (`*x`) to the current character being iterated over (`y`), updating `y` with the result of `0` or `1`. note that as soon as we have matched all the search characters, no more matches will be identified (since a character will never `~` (match) a `0` or `1`)
* `x,` append this result to the list of characters to search for (essentially overloading the reduction to end up returning the desired output)
* `y_` if there was a match, drop the first character (if there wasn't a match, this is a no-op). this allows us to search for the next search character in the next iteration of the reduction
* `y@<>` do an APL-style expand with y and the generated boolean array (this fills with `" "`s)

An alternative blank-out value can be implemented by inserting e.g. `"*"^y` at the beginning of the function.

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

```
v¬yQić?ë0?

```

-1 byte by using `0` as filler character instead of `*`.

Try it online or verify all test cases.

**Explanation:**

```
v       # Loop over the characters `y` of the (implicit) input-sentence:
 ¬      #  Get the first character without popping the string
        #  (which uses the implicit input-target the first iteration)
  yQi   #  If this first character is equal to the current character `y`:
     ć  #   Extract the head of the target-string; pop and push the remainder-string and
        #   first character separated to the stack
      ? #   Pop and print this first character
    ë   #  Else:
     0? #   Print 0 instead

```

# Answer
> 9 votes
# C (gcc), ~~52~~ 44 bytes

Saved 8 bytes thanks to the man himself Arnauld!!!

```
f(s,t)char*s,*t;{for(;*s++=*s-*t?42:*t++;);}

```

Try it online!

Function takes two input strings and return the meme-formatted string in the first parameter.

### Explanation

```
f(s,t)char*s,*t;{       // function inputs two strings
   for(;                // loop
        *s              // until end of string s
          ++            // bumping s each loop
            =           // set character in s to...
             *s-*t?     // depending on whether it equals character in t
                   42:  // a '* if not equal
                   *t++ // or character in t and bump t if equal
        ;);
}

```

# Answer
> 9 votes
# Python 3.10.0a41, 56 bytes

```
f=lambda s,t:s and('*'+s)[x:=s[0]==t[:1]]+f(s[1:],t[x:])

```

Try it online!

Python 3.10 allows unparenthesized assignment expressions in indexes, which saves 2 bytes over 3.8 here, which is the newest version on TIO.

1This is the version I tested locally, this will probably work in future versions as well.

# Answer
> 8 votes
# APL(Dyalog Unicode), ~~27 25~~ 20 bytes SBCS

```
({w↓⍨←⍵=⊃w,0}¨⍞)\w←⍞

```

Try it on APLgolf!

A tradfn submission which takes the two values from STDIN.

Inspired by coltim's K answer.

Uses space as the blotting character.

-2 and -5 bytes from Adám!

The expand operation `\` uses a bitmask to insert spaces between the elements of the input.

`1 0 0 1 0 0/'hi' → 'h i '`

## Explanation

```
({w↓⍨←⍵=⊃w,0}¨⍞)\w←⍞
                 w←⍞ store target word in w
                \    expand using the following bitmask:
 {          }¨⍞      for each character of the source word:
      ⍵=⊃w,0          is the character equal to the first one in w?
                      return that
  w↓⍨←                then drop that many characters from w (0 or 1)

```

# Answer
> 7 votes
# Ruby `-pl`, ~~38~~ 37 bytes

```
->t{gsub(/./){$&==t[0]?$&+t[0]*=0:0}}

```

Try it online!

Takes the sentence from STDIN and the target word as the lambda argument. Uses `0` as the blank-out character, an idea borrowed from @Arnauld's JavaScript answer, which saves a byte over using `*`.

For each character in the sentence:

* If it is the same as the first character of the target word, retain it. Then remove the first character of the target word (`t[0]*=0` is a slightly obfuscated equivalent to `t[0]=''`).
* Otherwise, replace it with `0`.

# Answer
> 5 votes
# , ~~102~~ 98 bytes

```
function(s,w,`[`=substring){for(i in 1:nchar(s))`if`(s[i,i]!=w[1,1],substr(s,i,i)<-"*",w<-w[2]);s}

```

Try it online!

```
function(s,w,            # s=sentence, w=word
  `[`=substring)         # `[` = alias to substring function
  {for(i in 1:nchar(s))  # loop over all the indexes of characters in s
    `if`(s[i,i]!=w[1,1], # if it isn't the same as the first character in w
    substr(s,i,i)<-"*",  # change it to a '*'
    w<-w[2]);            # otherwise leave it and remove the first character in w
 s                       # finally, return whatever's left in s

```

---

Or, with vectors of characters (instead of strings) as input & output (thanks to user for the suggestion):

# , 75 bytes

```
function(s,w)sapply(s,function(l)`if`(length(w)&l==w[1],{w<<-w[-1];l},'*'))

```

Try it online!

# Answer
> 5 votes
# Perl 5 `-plF`, 31 bytes

```
$_=<>;s/./$&ne$F[0]||shift@F/ge

```

Try it online!

Input is on two lines. The first line is the target word. The second line is the sentence. Uses `1` as the blanking character.

# Answer
> 5 votes
# Japt, 9 bytes

```
®¥VÎ?Vj:Q

```

Try it

```
input:
 > sentence as a string
 > target as a char array
output blanked out with "

®          - for each char in sentence:
 ¥VÎ?      -  == to first element in target?
     Vj    - returns first element and remove it from array
       :Q  - character "

```

# Answer
> 5 votes
# k9 L2021.01.29, 31 bytes

```
{(y,$0)(-1{*(x<)#y}\(=x)y)?!#x}

```

`(=x)y` get indices in sentence for each letter in target

`-1{*(x<)#y}\[target indices]` get each target letter's first index in the sentence that's greater than the last target index we took (ie always looking ahead)

`[first indices]?!#x` get position of each sentence index in the 'first target indices' list, defaulting to the list's length if not found

`(y,$0)[index list]` index into target word with 'blank char' suffix.

EDIT: assuming we want `*` as fill, we can use coltim's awesome ngn/k answer to get to 24 bytes:

```
{`c"*"|x*y{y_x,y~:*x}/x}

```

# Answer
> 4 votes
# Python 3, ~~90~~ ~~80~~ 81 bytes

-10 bytes (thanks to @Danis)

-Fixed error when trying to access first character (thanks for @xnor for reporting)

+1 byte: Fixing return error

```
def f(t,g,i=0):
 l=['*']*len(t)
 for c in g:i=t.find(c,i);l[i]=c*(i>=0)
 return l

```

Try it online!

# Answer
> 4 votes
# Charcoal, 19 bytes

```
≔⪪⮌⁺Ｓ¶¹θ⭆Ｓ∧⁼ι§θ±¹⊟θ

```

Try it online! Link is to verbose version of code. Takes input in the order target, string. Output uses `0` as filler (+1 byte to use an arbitrary filler character). Explanation:

```
≔⪪⮌⁺Ｓ¶¹θ

```

Append a newline to the input target, reverse it, and split it into characters.

```
⭆Ｓ∧⁼ι§θ±¹⊟θ

```

Loop over the input string, replacing each character with `0`, unless the character matches the last element of the above list, in which case pop that element instead.

# Answer
> 4 votes
# Racket, 140 bytes

```
(define(f s t[a'()])(if(null? s)(reverse a)(if(char=?(car s)(if(null? t)#\*(car t)))(f(cdr s)(cdr t)(cons(car s)a))(f(cdr s)t(cons #\*a)))))

```

Try it online!

I know, this is super long and silly.

# Answer
> 4 votes
# Oracle SQL, 225 bytes

Its not a golfing language, but ...

```
WITH r(s,w,a,b,c,l)AS(SELECT s,w,1,1,'',LENGTH(s) FROM t UNION ALL SELECT s,w,a+1,DECODE(SUBSTR(s,a,1),SUBSTR(w,b,1),b+1,b),c||DECODE(SUBSTR(s,a,1),SUBSTR(w,b,1),SUBSTR(w,b,1),0),l FROM r WHERE a<=l)SELECT c FROM r WHERE a>l

```

Which assumes a table `t` with columns `s` (sentence) and `w` (word) and uses `0` as the masking character.

A neatly formatted version (which also outputs the sentence and word) is:

```
WITH r(sentence,word,sentence_pos,word_pos,output,len)AS(
  SELECT s,
         w,
         1,
         1,
         '',
         LENGTH(s)
  FROM t
  UNION ALL
  SELECT sentence,
         word,
         sentence_pos+1,
         DECODE(
           SUBSTR(sentence,sentence_pos,1),
           SUBSTR(word,word_pos,1),
           word_pos+1,
           word_pos
         ),
         output||DECODE(
           SUBSTR(sentence,sentence_pos,1),
           SUBSTR(word,word_pos,1),
           SUBSTR(word,word_pos,1),
           0
         ),
         len
  FROM   r
  WHERE  sentence_pos<=len
)
SELECT sentence,
       word,
       output
FROM   r
WHERE  sentence_pos>len

```

Which, for the sample data:

```
CREATE TABLE t(s,w) AS
SELECT 'I do not control the speed at which lobsters die', 'code' FROM DUAL UNION ALL
SELECT 'testcase string', 'tas' FROM DUAL UNION ALL
SELECT 'uglhwagp qvyntzmf','ulhwagpqvyntzmf' FROM DUAL UNION ALL
SELECT 'qrkacxx wwfja jsyjdffa vwfgxf','qcfvf' FROM DUAL UNION ALL
SELECT 'z wzsgovhh jopw igcx muxj xmmisxdn t lmb','gcujxlb' FROM DUAL UNION ALL
SELECT 'kxf jgmzejypb ya','e' FROM DUAL UNION ALL
SELECT 'fe oxyk y','ex' FROM DUAL UNION ALL
SELECT 'o wr fmik','owrfmik' FROM DUAL UNION ALL
SELECT 'pgezt yozcyqq drxt gcvaj hx l ix xemimmox','e' FROM DUAL UNION ALL
SELECT 'kqclk b hkgtrh','k' FROM DUAL UNION ALL
SELECT 'sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw','crwqqhxl' FROM DUAL UNION ALL
SELECT 'teatsase','tas' FROM DUAL;

```

Outputs:

> ```
> SENTENCE                                            | WORD            | OUTPUT
> :-------------------------------------------------- | :-------------- | :--------------------------------------------------
> teatsase                                            | tas             | t0a0s000
> fe oxyk y                                           | ex              | 0e00x0000
> o wr fmik                                           | owrfmik         | o0wr0fmik
> kqclk b hkgtrh                                      | k               | k0000000000000
> testcase string                                     | tas             | t0000as00000000
> kxf jgmzejypb ya                                    | e               | 00000000e0000000
> uglhwagp qvyntzmf                                   | ulhwagpqvyntzmf | u0lhwagp0qvyntzmf
> qrkacxx wwfja jsyjdffa vwfgxf                       | qcfvf           | q000c00000f000000000000v0f000
> z wzsgovhh jopw igcx muxj xmmisxdn t lmb            | gcujxlb         | 00000g000000000000c000u0j0x0000000000l0b
> pgezt yozcyqq drxt gcvaj hx l ix xemimmox           | e               | 00e00000000000000000000000000000000000000
> I do not control the speed at which lobsters die    | code            | 000000000co00000000000000d000000000000000e000000
> sia prcrdfckg otqwvdv wzdqxvqb h xclxmaj xjdwt lzfw | crwqqhxl        | 000000cr000000000w0000000q00q00h0x0l000000000000000
>
> ```

*db\<\>fiddle here*

# Answer
> 4 votes
# brainfuck, ~~131~~ ~~106~~ ~~96~~ 89 bytes

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

```

Input is taken as `sentence\ntarget` where `\n` is a newline

Try it online!

-25 bytes (thanks to @cairdcoinheringaahing)

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~38~~ 32 bytes

-6 bytes by using a space instead of `*` as a blank out character.

A port of my Python answer. Assumes `⎕IO←0`.

```
{×≢⍵:(⊃x↑⍺),(⍺↓⍨x←⊃=⌿↑⍺⍵)∇1↓⍵⋄⍵}

```

Try it online!

**Commented**:

```
{ ... }         ⍝ A dfn taking two arguments:
                ⍝ - the target word as the left argument ⍺
                ⍝ - and the sentence as the right argument ⍵
×≢⍵:            ⍝ if the length of ⍵ is positive:
        ↑⍺⍵     ⍝ mix ⍺ and ⍵ into a character matrix, padding the shorter with spaces
      =⌿        ⍝ for each row, check if the two characters are equal
     ⊃          ⍝ take the first result
                ⍝ this is now ⍺[0] = ⍵[0], but this is 1 if ⍺ is empty and ' ' = ⍵[0]
   x←           ⍝ and store it in x
⍺↓⍨x            ⍝ drop x (0 or 1) characters from ⍺
∇               ⍝ and call the dfn recursively with this value
 1↓⍵            ⍝ and with ⍵ without he first character

(          ),   ⍝ prepend to the result of the recursive call
   ⊃            ⍝ the first character of
      x↑⍺       ⍝ take the first x characters of ⍺
                ⍝ if one of these strings is empty, ⊃ and ↑ use a space as a default value

⋄⍵              ⍝ if the length of ⍵ is not positive, return ⍵

```

# Answer
> 4 votes
# Husk, 15 bytes

```
«S↓₁λ?←¹'*₁
€↑1

```

Try it online!

It took a while, but here's a short(ish) working solution.

### Explanation

The second line is a helper function, it shortens the program because we would have to call it twice, and it would need brackets both times if it was inlined.

```
€↑1       Input: a string and a character, Output: 0 or 1
 ↑1       Get the first 1 characters of the string
€         Return the index of the character in this substring (0 if missing)

```

This function tells us if the given character is the same as the character at the beginning of the string. There would be a simpler way of doing this (`=←`), but  on an empty string returns a space character, and this would mess up things.

The rest of the program is a call to mapacL (`«`), which scans a list using two functions, one to update the internal accumulator and the other one to generate the output. In practice, we will loop through the sentence character by character, our accumulator will start as the target word, and at each step we will update the accumulator using the current input character and the first function (`S↓₁`), and we will generate one output character using the accumulator, the current input character, and the second function (`λ?←¹'*₁`).

Updating the accumulator means discarding the first character from it if it matches the current input character:

```
S↓₁     Input: accumulator and current character, Output: new accumulator
  ₁     Call helper function (1 if character matches, 0 if it does not)
 ↓      Drop that many characters
S        from the first input (accumulator)

```

Generating output characters means returning the character itself if it matches, and returning `'*'` if it does not:

```
λ?←¹'*₁    Input: accumulator and current character, Output: character or '*'
      ₁    Call helper function (1 if character matches, 0 if it does not)
 ?         If 1:
  ←          get the first character from
λ  ¹           the accumulator
           Else:
    '*       Return '*'

```

# Answer
> 3 votes
# Stax, ~~24 18 17~~ 16 bytes

```
ù←⌐0ø\d▀→"ε╞☺Γ|▓

```

Run and debug it

-6 bytes, following Dingus's idea.

-1 byte from recursive. (`h=` → `h`)

-1 byte, using `\0` as a filler character.

# Answer
> 3 votes
# Retina 0.8.2, 37 bytes

```
.
_$&
+`.(.)((_.)*¶)_\1
$1_$2
(.).
$1

```

Try it online! Uses `_` as the filler. Explanation:

```
.
_$&

```

Prepend a `_` to every character (both of the string and the target).

```
+`.(.)((_.)*¶)_\1
$1_$2

```

Find a character which is not before a character that has already been swapped that matches the first character of the original target, and swap it with its preceding `_`, removing it from the target, and repeat until the target is empty.

```
(.).
$1

```

Remove alternate characters, i.e. keeping the `_`s unless the target character was swapped.

# Answer
> 3 votes
# Red, 71 bytes

```
func[s t][c: take t parse s[any[change[not c skip]"*"| c(c: take t)]]s]

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 42 bytes

```
c_~f[a:c_:"*",b___]~d___=a<>f[b]@d
_f[]=""

```

Try it online!

Input two characters sequences as `f[word][sentence]`.

# Answer
> 3 votes
# Elixir, ~~184~~ 169 bytes

```
defmodule A do
def f x,y do
cond do
x==""->x
q(x)==q(y)->q(y)<>f p(x),p y
1->"*"<>f p(x),y
end
end
def p(x)do
String.slice(x,1..-1)
end
def q(x)do
String.at(x,0)
end
end

```

Try it online!

# Answer
> 3 votes
# PowerShell, ~~63~~ 57 bytes

```
$t,$s=$args
-join($s|%{"*$_"[($c=$_-ceq$t[+$i])];$i+=$c})

```

Try it online!

-6 bytes thanks to mazzy!

# Answer
> 2 votes
# C (gcc), ~~49~~ 46 bytes

-3 thanks to @ceilingcat

```
f(s,w)char*s,*w;{for(;*s;s++)*s-*w?*s=42:w++;}

```

Try it online!

Just noticed that there's another C answer that is even shorter. Nevermind, I leave mine here.

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 134 bytes

```
	S =INPUT
	W =INPUT
N	W LEN(1) . M REM . W	:F(O)
	S ARB . L M REM . S
	O =O DUPL('*',SIZE(L)) M	:(N)
O	OUTPUT =O DUPL('*',SIZE(S))
END

```

Try it online!

# Answer
> 2 votes
# ARM Thumb-2 machine code, 24 bytes

Machine code

```
f811 2b01 7803 4293 bf18 232a f800 3b01
d1f8 2a00 d1f4 4770

```

Commented assembly:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .globl lobstah
        .thumb_func
        // C callable.
        // void lobstah(char *sentence, const char *target);
        // Input:
        //   sentence (null terminated string): r0
        //   target (null terminated string): r1
        // Output:
        //   sentence is modified in place
        //
        // This is nothing but the obvious approach: a linear
        // search loop. Sometimes, that's best. ¯\_(ツ)_/¯
lobstah:
.Lnext_target:
        // Load next byte from target, increment (wide insn)
        ldrb    r2, [r1], #1
        // Search
.Lsearch_loop:
        // Load byte from sentence
        ldrb    r3, [r0]
        // Is it our target?
        cmp     r3, r2
        // If it wasn't, replace with a '*'
        it      ne
        movne   r3, #'*'
        // Store back and increment (wide insn)
        strb    r3, [r0], #1
        // Loop while we don't have a match
        // (the flags were not modified since the cmp)
        bne     .Lsearch_loop
.Lsearch_loop.end:
        // Loop unless we reached the null terminator.
        cmp     r2, #0
        bne     .Lnext_target
.Lend:
        // Return
        bx      lr

```

Try it online! (sorta)

It is nothing but the obvious approach, a linear search loop. You really can't make anything smaller than that. ♂

# Answer
> 2 votes
# Rust, 123 bytes

```
|m:&str,v:&str|{m.chars().fold(v.chars().peekable(),|mut a,c|{print!("{}",if a.peek()==Some(&c){a.next();c}else{'*'});a});}
```

Attempt This Online!

Adapted from my answer to "Backronymiser"

# Answer
> 2 votes
# Thunno 2 `cJ`, 10 bytes

```
Xıxh=?ẋḣ:0

```

Try it online!

Uses `0` as the filler character.

#### Explanation

```
Xıxh=?ẋḣ:0  # Implicit input
X           # Put the first input string in x
 ı          # Map over the second input string:
  xh=       #   Does it equal the first character of x?
     ?      #   If it does:
      ẋḣ    #     Remove the first character of x
            #     (and the current character remains on top)
        :   #   Otherwise:
         0  #     Push a 0 instead (as a filler)
            # Implicit output, joined into a string

```

# Answer
> 1 votes
# Java (JDK), ~~91~~ 90 bytes

Saved 1 byte thanks to ceilingcat

```
s->t->{var r="";for(int a=0,b=0;a<s.length&b<t.length;)r+=s[a++]==t[b]?t[b++]:2;return r;}

```

Try it online!

Takes input as `char[]`s, uses an unprintable character (2) to blank letters out (+1 bytes to use a printable character).

# Answer
> 1 votes
# Husk, 35 bytes

```
ṁ←tU¡λ?:;←!2¹mtt¹ė" "t!2¹!3¹Ë←t)ė"

```

Try it online!

A very clunky infinite list based solution, but so far the only one that works correctly, so I decided to post it.

# Answer
> 1 votes
# PHP, 111 bytes

```
$i=0;$c='';foreach(str_split($argv[2])as$k){if($k==str_split($argv[1])[$i]){$c.=$k;$i++;}else{$c.='*';}}echo$c;

```

Explanation:

```
$i=0;$c=''; //init vars (index, tracker)
foreach(str_split($argv[2])as$k){ //for each char in string 2
if($k==str_split($argv[1])[$i]){ // if char in string 2 matches char searched for
  $c.=$k;$i++; //add char to tracker + increment index
}else{$c.='*';} // else add * to tracker
}echo$c; //output tracker

```

Try it online!

Input as args - arg 1 is string to find, arg 2 is string to look in.

# Answer
> 1 votes
# Vyxal `s`, 10 bytes

```
£ƛ¥h=[&Ḣ|×

```

Try it Online!

# Answer
> 1 votes
# Jelly, 15 bytes

```
⁸©µ⁹µ®1ị®Ḣ¤0=?)

```

Try it online!

Absolutely TERRIBLE.

```
⁸©µ⁹µ®1ị®Ḣ¤0=?)  - Dyadic link f(k, s) where k is the "word" and s is the "sentence"
⁸©               - Copy k to the register
  µ              - Begin a new monadic chain f(s) to prevent k from being implicitly printed
   ⁹µ         )  - Map over s:
     ®1ị         -  Get the first character of the register
            =?   -  Is it equal to the current character in s?
        ®Ḣ¤      -   If so, then remove the first character from the register and push it
           0     -   Else, just use 0

```

# Answer
> 1 votes
# Arturo, 42 bytes

```
$[s t][i:0map s'c->(=c<=t\[i])?['i+1]->'*]

```

Try it!

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


# Question
Title: Given an input, print all exponents where the base and power sum to the input
So this is my first challenge on this site.

The challenge is to take in an input integer \\$n\\$, which will be positive, and print, in ascending order (\\$1\\$ to \\$n\\$, **including n**), the output of \\$i^{(n-i)}\\$ (where \\$i\\$ is the current integer).

# Example

Given the input 5, the program will print:

```
1
8
9
4
1

```

\\$1^4\\$ is 1 and \\$1+4=5\\$
\\$2^3\\$ is 8 and \\$2+3=5\\$
\\$3^2\\$ is 9 and \\$3+2=5\\$
\\$4^1\\$ is 4 and \\$4+1=5\\$
\\$5^0\\$ is 1 and \\$5+0=5\\$

# Input and Output

Input will be in the form of a positive integer. Output will be a list of numbers, delimited by either commas or new lines.

This is , so shortest code wins.

# Answer
> 6 votes
# APL (Dyalog Unicode), ~~8~~ 5 bytes

```
⍳*⊢-⍳

```

Try it online!

Anonymous prefix tacit function. TIO tests for the range \[1..10\].

Thanks @lirtosiast for 3 bytes.

### How:

```
⍳*⊢-⍳ ⍝ Tacit function
    ⍳ ⍝ Range. ⍳n generates the vector [1..n].
  ⊢- ⍝ Subtracted from the argument. The vector is now [n-1,n-2,...,0]
⍳*    ⍝ Exponentiate using the range [1..n] as base. The result is the vector
      ⍝ [1^(n-1), 2^(n-2), 3^(n-3),...]

```

# Answer
> 5 votes
# Perl 6, 19 bytes

```
{^$_+1 Z**[R,] ^$_}

```

Try it online!

Anonymous code block that takes a number and returns a list. Zip exponents the range `1 to input` and the range `input-1 to 0`

# Answer
> 5 votes
## Haskell, 23 bytes

```
f i=[x^(i-x)|x<-[1..i]]

```

Try it online!

Alternative version, also 23 bytes:

```
f i=(^)<*>(i-)<$>[1..i]

```

# Answer
> 5 votes
# Aheui (esotope), ~~193~~ 164 bytes (56 chars)

```
방빠싹받분샥퍼붇바파쟈뿌차샦히망맣여
타빠바푸투반또분뽀뿌서썪삯타삯받반타
석차샦져쌲볼어타토싻삭빠쏛ㅇ또섞썪뻐

```

Try it online!

Try it on AVIS(**Korean**); just copy and paste code above, press start button, input a number, see how it moves. To see output, press the **\>\_** icon on left side.

---

It's not golfed much, but I give it a shot.

# Answer
> 5 votes
# Japt, 5 bytes

```
õ_p´U

```

Try it

```
õ         :Range [1,input]
 _        :Map
  p       :  Raise to the power of
   ´U     :  Input decremented

```

# Answer
> 4 votes
# Pyth, 5 bytes

```
_m^-Q

```

Try it online!

Optimally encoded this would be 4.106 bytes.

```
_                reverse of the following list:
 m               map the following lambda d:
  ^                (N-d)**d
   -Qd
      d
       Q         over [0,...,N-1]

```

# Answer
> 4 votes
# , 10 bytes

```
(>:^|.)@i.

```

Try it online!

## If we really need to separate the numbers by a newline:

# , 13 bytes

```
,.@(>:^|.)@i.

```

Try it online!

# Answer
> 3 votes
# Jelly, 5 bytes

```
R*ḶU$

```

Try it online!

```
R                [1,...,n]
 *               to the power of
  ḶU$            [0,...,n-1] reversed

```

# Answer
> 3 votes
# Octave, 18 bytes

```
@(n)(t=1:n).^(n-t)

```

Try it online!

Thanks Luis Mendo, using internal variable saves 3 bytes.

# Answer
> 3 votes
# PHP, 32 bytes

```
while($argn)echo++$i**--$argn,_;

```

Run as pipe with `-nR` or try it online.

# Answer
> 3 votes
# Jelly, 4 bytes

```
*ạ¥€

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), ~~33~~ 32 bytes

```
n=>(g=i=>--n?++i**n+[,g(i)]:1)``

```

Try it online!

-3 bytes with credits to @Shaggy, and -1 byte by @l4m2!

# JavaScript (Node.js), 36 bytes

```
f=(n,i=1)=>n--?[i++**n,...f(n,i)]:[]

```

Try it online!

# JavaScript (Node.js), 37 bytes

```
n=>[...Array(n)].map(x=>++i**--n,i=0)

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~24~~ ~~20~~ 18 bytes

```
(x=Range@#)^(#-x)&

```

Try it online!

-4 thanks @lirtosiast.

# Answer
> 2 votes
# MathGolf, 6 bytes

```
rx\╒m#

```

Try it online!

# Answer
> 2 votes
# Python 2, 40 bytes

```
lambda n:[i**(n-i)for i in range(1,n+1)]   #Outputs a list

```

Try it online!

# Python 2, 41 bytes

```
n,i=input(),0
exec"print(n-i)**i;i+=1;"*n   #Prints in reversed order

```

Try it online!

# Answer
> 2 votes
# Ruby, 27 bytes

```
->n{(1..n).map{|r|r**n-=1}}

```

Try it online!

# Answer
> 2 votes
## QBasic, ~~35~~33 bytes

Thank you @Neil for 2 bytes!

```
INPUT a
FOR b=1TO a
?b^(a-b)
NEXT

```

Slightly expanded version on REPL.IT because the interpreter in't entirely up-to-spec.

**Output**

```
QBasic (qb.js)
Copyright (c) 2010 Steve Hanov

   5
1
8
9
4
1

```

# Answer
> 2 votes
# Retina, 35 bytes

```
.+
*
_
$$.($.'*$($.>`$*)_¶
%~`^
.+¶

```

Try it online! Explanation:

```
.+
*

```

Convert the input to unary.

```
_

```

Match each position. This then sets several replacement variables. `$`` becomes the left of the match; `$>`` modifies this to be the left and match; `$.>`` modifies this to take the length, i.e. the current index. `$'` meanwhile is the right of the match, so `$.'` is the length i.e. the current exponent.

```
$$.($.'*$($.>`$*)_¶

```

Create a string `$.(` plus `$.'` repetitions of `$.>`*` plus `_`. For an example, for an index of 2 in an original input of 5, `$.'` is 3 and `$.>`` is 2 so the resulting string is `$.(2*2*2*_`. This conveniently is a Retina replacement expression that caluclates 2³. Each string is output on its own line.

```
%~`^
.+¶

```

For each line generated by the previous stage, prefix a line `.+` to it, turning it into a replacement stage, and evaluate that stage, thereby calculating the expression.

# Answer
> 2 votes
# F# (.NET Core), 42 bytes

```
let f x=Seq.map(fun y->pown y (x-y))[1..x]

```

Try it online!

# Answer
> 2 votes
# Java, 59 Bytes

```
for(int i=1;a+1>i;i++)System.out.println(Math.pow(i,a-i));

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 46 bytes

```
x=>new int[x].Select((_,i)=>Math.Pow(i+1,--x))

```

Try it online!

# Answer
> 2 votes
# MATL, 5 bytes

```
:Gy-^

```

Try it online!

### Explanation

Consider input `5` as an example.

```
:     % Implicit input. Range
      % STACK: [1 2 3 4 5]
G     % Push input again
      % STACK: [1 2 3 4 5], 5
y     % Duplicate from below
      % STACK: [1 2 3 4 5], 5, [1 2 3 4 5]
-     % Subtract, element-wise
      % STACK: [1 2 3 4 5], [4 3 2 1 0]
^     % Power, element-wise. Implicit display
      % STACK: [1 8 9 4 1]

```

# Answer
> 1 votes
# Clean, 37 bytes

```
import StdEnv
$n=[i^(n-i)\\i<-[1..n]]

```

Try it online!

Defines `$ :: Int -> [Int]` taking an integer and returning the list of results.

```
$ n                // function $ of n
 = [i ^ (n-i)      // i to the power of n minus i
    \\ i <- [1..n] // for each i in 1 to n
   ]

```

# Answer
> 1 votes
# , 34 bytes

```
x=1:scan();cat(x^rev(x-1),sep=',')

```

Try it online!

# Answer
> 1 votes
# Lua, 43 41 bytes

-2 bytes thanks to *@Shaggy*

```
s=io.read()for i=1,s do print(i^(s-i))end

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
LD<Rm

```

Port of *@lirtosiast*'s Jelly answer.

Try it online.

**Explanation:**

```
L      # List in the range [1, (implicit) input integer]
       #  i.e. 5 → [1,2,3,4,5]
 D<    # Duplicate this list, and subtract 1 to make the range [0, input)
       #  i.e. [1,2,3,4,5] → [0,1,2,3,4]
   R   # Reverse it to make the range (input, 0]
       #  i.e. [0,1,2,3,4] → [4,3,2,1,0]
    m  # Take the power of the numbers in the lists (at the same indices)
       # (and output implicitly)
       #  i.e. [1,2,3,4,5] and [4,3,2,1,0] → [1,8,9,4,1]

```

# Answer
> 1 votes
# R, 22 bytes

```
n=scan();(1:n)^(n:1-1)

```

Fairly self-explanatory; note that the `:` operator is higher precendence than the `-` operator so that `n:1-1` is shorter than `(n-1):0`

If we are allowed to start at 0, then we can lose two bytes by using `(0:n)^(n:0)` avoiding the need for a -1.

# Answer
> 1 votes
# Charcoal, 9 bytes

```
Ｉ⮌ＥＮＸ⁻θιι

```

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

```
   Ｎ        Input as a number
  Ｅ         Map over implicit range
       ι    Current value
     ⁻      Subtracted from
      θ     First input
    Ｘ       Raised to power
        ι   Current value
 ⮌          Reverse list
Ｉ           Cast to string
             Implicitly print on separate lines

```

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 55 bytes

```
v=>Enumerable.Range(0,v--).Select(i=>Math.Pow(i+1,v--))

```

Try it online!

# Answer
> 1 votes
# C++ (clang), ~~80 bytes~~, ~~71 bytes~~, ~~63 bytes~~, ~~59 bytes~~, 56 bytes

```
int n,c=1;cin>>n;for(;c<=n;++c){cout<<pow(c,n-c)<<endl;}

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-n`, 21 bytes

```
say++$\**--$_ while$_

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 22 bytes

```
n->[i^(n-i)|i<-[1..n]]

```

Try it online!

# Answer
> 1 votes
# PowerShell, 39 bytes

```
param($n)1..$n|%{"1"+"*$_"*($n-$_)|iex}

```

Try it online!

Because exponents are expensive in Powershell, this works by using invoke-expression to parse and calculate the string "1\*n\*n...\*n" Works because the first and last entry are always 1.

# Answer
> 1 votes
# Gambit Scheme (gsi), 52 bytes

```
(lambda(x)(map(lambda(y)(expt y(-x y)))(iota x 1)))

```

For some reason this code does not appear to work on TIO. It works fine on my machine.

**Explanation:**

```
(lambda(x)(map(lambda(y)(expt y(- x y)))(iota x 1)))    Full program
(lambda(x)                                        )    Anonymous function with arg x
          (map(lambda(y)              )(iota x 1))     Map over the range 1 to input
                        (expt y                        Raises the mapped value to...
                               (- x y)                 The input value minus the mapped value (this powers the list by the reverse)

```

# Answer
> 1 votes
# Thunno 2, 5 bytes

```
RD$_*

```

Try it online!

#### Explanation

```
RD$_*  # Implicit input
R      # Push [1..input]
 D     # Duplicate
  $_   # Subtract from input
    *  # Exponentiate
       # Implicit output

```

# Answer
> 0 votes
# C (gcc) (`-lm`), 52 bytes

```
f(n,i){for(i=n;i--;printf("%.0f\n",pow(n-i,i)));}

```

Try it online!

# Answer
> 0 votes
# APL(NARS), 11 chars, 22 bytes

```
{⍪⍵*⌽⍵-1}∘⍳

```

test:

```
  f←{⍪⍵*⌽⍵-1}∘⍳
  f 5
1
8
9
4
1

```

# Answer
> 0 votes
**SAS, 71 bytes**

```
data a;input n;o=cat(1);do x=1 to n-1;o=catx(',',(n-x)**x,o);end;cards;

```

Input goes after the `cards;` statement, separated by newlines, like so:

```
data a;input n;o=cat(1);do x=1 to n-1;o=catx(',',(n-x)**x,o);end;cards;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

```

Outputs a dataset containing the input `n`, and comma-separated output string `o` (and also helper variable `x`)

```
+----+------------------------------------------------------------------------------------------+----+
| n  |                                            o                                             | x  |
+----+------------------------------------------------------------------------------------------+----+
¦ 1  ¦ 1                                                                                ¦ 1  ¦
¦ 2  ¦ 1,1                                                                                ¦ 2  ¦
¦ 3  ¦ 1,2,1                                                                                ¦ 3  ¦
¦ 4  ¦ 1,4,3,1                                                                                ¦ 4  ¦
¦ 5  ¦ 1,8,9,4,1                                                                                ¦ 5  ¦
¦ 6  ¦ 1,16,27,16,5,1                                                                           ¦ 6  ¦
¦ 7  ¦ 1,32,81,64,25,6,1                                                                        ¦ 7  ¦
¦ 8  ¦ 1,64,243,256,125,36,7,1                                                                  ¦ 8  ¦
¦ 9  ¦ 1,128,729,1024,625,216,49,8,1                                                            ¦ 9  ¦
¦ 10 ¦ 1,256,2187,4096,3125,1296,343,64,9,1                                                     ¦ 10 ¦
¦ 11 ¦ 1,512,6561,16384,15625,7776,2401,512,81,10,1                                             ¦ 11 ¦
¦ 12 ¦ 1,1024,19683,65536,78125,46656,16807,4096,729,100,11,1                                   ¦ 12 ¦
¦ 13 ¦ 1,2048,59049,262144,390625,279936,117649,32768,6561,1000,121,12,1                        ¦ 13 ¦
¦ 14 ¦ 1,4096,177147,1048576,1953125,1679616,823543,262144,59049,10000,1331,144,13,1            ¦ 14 ¦
¦ 15 ¦ 1,8192,531441,4194304,9765625,10077696,5764801,2097152,531441,100000,14641,1728,169,14,1 ¦ 15 ¦
+----------------------------------------------------------------------------------------------------+

```

# Answer
> 0 votes
# C (clang), 47 bytes

```
i;f(a){for(i=a;i;printf("%.f,",pow(i,a-i--)));}

```

Try it online!

Prints in reverse order, delimited with commas.

# Answer
> 0 votes
# Arturo, 20 bytes

```
$->n[map n'i->i^n-i]

```

Try it!

---
Tags: code-golf, math, arithmetic
---


title: Proper Divisor mash-up

text:
# Question
Title: Proper Divisor mash-up
A *proper divisor* is a divisor of a number *n*, which is not *n* itself. For example, the proper divisors of 12 are 1, 2, 3, 4 and 6.

You will be given **an integer** *x*, *x* ≥ 2, *x ≤ 1000*. Your task is to sum all the ***highest* proper divisors** of the integers from *2* to *x* (inclusive) (OEIS A280050).

### Example (with `x = 6`):

* Find all the integers between 2 and 6 (inclusive): 2,3,4,5,6.
* Get the proper divisors of all of them, and pick the highest ones from each number:

+ 2 -\> **1**
    + 3 -\> **1**
    + 4 -\> 1, **2**
    + 5 -\> **1**
    + 6 -\> 1, 2, **3**.
* Sum the highest proper divisors: `1 + 1 + 2 + 1 + 3 = 8`.
* The final result is 8.

# Test Cases

```
Input  |  Output
-------+---------
       |
 2     | 1
 4     | 4
 6     | 8
 8     | 13
 15    | 41
 37    | 229
 100   | 1690
 1000  | 165279

```

# Rules

# Answer
> 13 votes
# Oasis, 4 bytes

### Code:

```
nj+U

```

Try it online!

### Explanation:

Extended version:

```
nj+00

    0   = a(0)
   0    = a(1)

a(n) =

n       # Push n
 j      # Get the largest divisor under n
  +     # Add to a(n - 1)

```

# Answer
> 5 votes
# Brachylog, 10 bytes

```
⟦bb{fkt}ᵐ+

```

Try it online!

# Answer
> 5 votes
# Pyth, ~~13~~ ~~9~~ 8 bytes

1 byte thanks to jacoblaw.

```
tsm*FtPh

```

Test suite.

## How it works

The largest proper divisor is the product of the prime factors except the smallest one.

# Answer
> 5 votes
# Python 2, 50 bytes

```
f=lambda n,k=2:n/k and(f(n,k+1),n/k+f(n-1))[n%k<1]

```

This is *slow* and can't even cope with input **15** on TIO.

Try it online!

However, memoization (*thanks @musicman523*) can be used to verify all test cases.

Try it online!

### Alternate version, 52 bytes

At the cost of 2 bytes, we can choose whether to compute `f(n,k+1)` or `n/k+f(n-1)`.

```
f=lambda n,k=2:n>1and(n%k and f(n,k+1)or n/k+f(n-1))

```

With some trickery, this works for all test cases, even on TIO.

Try it online!

# Answer
> 5 votes
## Husk, 7 bytes

```
ṁȯΠtptḣ

```

Try it online!

## Explanation

Husk has no built-in for computing the divisors directly (yet), so I'm using prime factorization instead. The largest proper divisor of a number is the product of its prime factors except the smallest one. I map this function over the range from 2 to the input, and sum the results.

```
ṁȯΠtptḣ  Define a function:
      ḣ  Range from 1 to input.
     t   Remove the first element (range from 2).
ṁ        Map over the list and take sum:
 ȯ        The composition of
    p     prime factorization,
   t      tail (remove smallest prime) and
  Π       product.

```

# Answer
> 4 votes
# Jelly, 6 bytes

```
ÆḌ€Ṫ€S

```

Try it online!

## How it works

```
ÆḌ€Ṫ€S
ÆḌ€    map proper divisor (1 would become empty array)
           implicitly turns argument into 1-indexed range
   Ṫ€  map last element
     S sum

```

# Answer
> 4 votes
## Haskell, ~~48~~ ~~46~~ 43 bytes

```
f 2=1
f n=until((<1).mod n)pred(n-1)+f(n-1)

```

Try it online!

Edit: @rogaos saved two bytes. Thanks!

Edit II: ... and @xnor another 3 bytes.

# Answer
> 4 votes
## JavaScript (ES6), 40 bytes

```
f=(n,i=2)=>n<2?0:n%i?f(n,i+1):n/i+f(n-1)
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

A number equals the product of its highest proper divisor and its smallest prime factor.

# Answer
> 4 votes
# MATL, 12 bytes

```
q:Q"@Z\l_)vs

```

Try it at MATL Online

**Explanation**

```
        % Implicitly grab input (N)
q       % Subtract one
:       % Create an array [1...(N-1)]
Q       % Add one to create [2...N]
"       % For each element
  @Z\   % Compute the divisors of this element (including itself)
  l_)   % Grab the next to last element (the largest that isn't itself)
  v     % Vertically concatenate the entire stack so far
  s     % Sum the result

```

# Answer
> 4 votes
# Japt, ~~8+2=10~~ ~~8~~ 6 bytes

```
òâ1 xo

```

Test it

* 1 byte saved thanks to ETHproductions.

---

## Explanation

```
    :Implicit input of integer U.
ò   :Generate an array of integers from 1 to U, inclusive
â   :Get the divisors of each number,
1   :  excluding itself.
x   :Sum the main array
o   :by popping the last element from each sub-array.
    :Implicit output of result

```

# Answer
> 4 votes
# Retina, ~~31~~ 24 bytes

7 bytes thanks to Martin Ender.

```
.+
$*
M!&`(1+)(?=\1+$)
1

```

Try it online!

## How it works

The regex `/^(1+)\1+$/` captures the largest proper divisor of a certain number represented in unary. In the code, the `\1+` is turned to a lookahead syntax.

# Answer
> 4 votes
# 05AB1E, ~~9~~ 8 bytes

-1 Byte thanks to Leaky Nun's prime factor trick in his Pyth answer

```
L¦vyÒ¦PO

```

Try it online!

### Explanation

```
L¦vyÒ¦PO
L¦       # Range [2 .. input]
  vy     # For each...
    Ò¦    # All prime factors except the first one
      P   # Product
       O  # Sum with previous results
         # Implicit print

```

Alternative 8 Byte solution (That doesnt work on TIO)

```
L¦vyÑ¨θO

```

and ofc alternative 9 Byte solution (That works on TIO)

```
L¦vyÑ¨®èO

```

# Answer
> 4 votes
# Python 2 (PyPy), ~~73~~ ~~71~~ 70 bytes

```
n=input();r=[0]*n;d=1
while n:n-=1;r[d+d::d]=n/d*[d];d+=1
print sum(r)

```

Not the shortest Python answer, but this just breezes through the test cases. TIO handles inputs up to **30,000,000** without breaking a sweat; my desktop computer handles **300,000,000** in a minute.

At the cost of **2 bytes**, the condition `n>d` could be used for a ~10% speed-up.

*Thanks to @xnor for the `r=[0]*n` idea, which saved 3 bytes!*

Try it online!

# Answer
> 4 votes
# Mathematica, 30 bytes

```
Divisors[i][[-2]]~Sum~{i,2,#}&

```

# Answer
> 3 votes
# PHP, 56 bytes

```
for($i=1;$v||$argn>=$v=++$i;)$i%--$v?:$v=!$s+=$v;echo$s;

```

Try it online!

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

```
f(A,B):-A=2,B=1;C is A-1,f(C,D),between(2,A,E),divmod(A,E,S,0),B is D+S.

```

Try it online!

# Answer
> 3 votes
# C# (.NET Core), 74 72 bytes

```
n=>{int r=0,j;for(;n>1;n--)for(j=n;--j>0;)if(n%j<1){r+=j;j=0;}return r;}

```

Try it online!

* 2 bytes shaved thanks to Kevin Cruijssen.

# Answer
> 3 votes
# Cubix, 27 ~~39~~ bytes

```
?%\(W!:.U0IU(;u;p+qu.@Op\;;

```

Try it online!

Cubified

```
      ? % \
      ( W !
      : . U
0 I U ( ; u ; p + q u .
@ O p \ ; ; . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Watch It Run

* `0IU` Set up the stack with an accumulator, and the starting integer. U-turn into the outer loop
* `:(?` duplicate the current top of stack, decrement and test
* `\pO@` if zero loop around the cube to a mirror, grab the bottom of stack, output and halt
* `%\!` if positive, mod, relect and test.
    + `u;.W` if truthy, u-turn, remove mod result and lane change back into inner loop
    + `U;p+qu;;\(` if falsey, u-turn, remove mod result, bring accumulator to top, add current integer (top) divisor push to bottom and u-turn. Clean up the stack to have just accumulator and current integer, decrement the integer and enter the outer loop again.

# Answer
> 2 votes
# Python 3, ~~69~~ ~~63~~ 59 bytes

4 bytes thanks to Dennis.

```
f=lambda n:n-1and max(j for j in range(1,n)if n%j<1)+f(n-1)

```

Try it online!

I set the recursion limit to 2000 for this to work for 1000.

# Answer
> 2 votes
# Actually, 12 bytes

```
u2x⌠÷R1@E⌡MΣ

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~78 75 73~~ 71 bytes

Not even close to Leaky nun's python answer in byte count.

```
f=lambda z:sum(max(i for i in range(1,y)if 1>y%i)for y in range(2,z+1))

```

Try it online!

# Answer
> 2 votes
# Pari/GP, ~~36~~ 30 bytes

```
n->sum(i=2,n,i/divisors(i)[2])

```

Try it online!

# Answer
> 2 votes
# Charcoal, 37 bytes

```
Ａ⁰βＦ…·²Ｎ«Ａ⟦⟧δＦ⮌…¹ι«¿¬﹪ικ⊞δκ»Ａ⁺β⌈δβ»Ｉβ

```

Try it online!

Link is to the verbose version. It took me almost all day to figure out how could I solve a non-ASCII-art-related question in Charcoal, but finally I got it and I am very proud of me. :-D

Yes, I am sure this can be golfed a lot. I just translated my C# answer and I am sure things can be done differently in Charcoal. At least it solves the `1000` case in a couple of seconds...

# Answer
> 2 votes
# Python 2 (PyPy), 145 bytes

Because turning code-golf competitions into fastest-code competitions is fun, here is an O(*n*) algorithm that, on TIO, solves *n* = **5,000,000,000** in 30 seconds. (Dennis’s sieve is O(*n* log *n*).)

```
import sympy
n=input()
def g(i,p,k,s):
 while p*max(p,k)<=n:l=k*p;i+=1;p=sympy.sieve[i];s-=g(i,p,l,n/l*(n/l*k+k-2)/2)
 return s
print~g(1,2,1,-n)

```

Try it online!

### How it works

We count the size of the set

*S* = {(*a*, *b*) | 2 ≤ *a**n*, 2 ≤ *b* ≤ largest-proper-divisor(*a*)},

by rewriting it as the union, over all primes p ≤ √n, of

*S**p* = {(*p**d*, *b*) | 2 ≤ *d**n*/*p*, 2 ≤ *b**d*},

and using the inclusion–exclusion principle:

|*S*| = ∑ (−1)*m* − 1 |*S**p*1 ∩ ⋯ ∩ *S**p**m*| over *m* ≥ 1 and primes *p*1 \< ⋯ \< *p**m* ≤ √n,

where

*S**p*1 ∩ ⋯ ∩ *S**p**m* = {(*p*1*p**m**e*, *b*) | 1 ≤ *e**n*/(*p*1*p**m*), 2 ≤ *b**p*1*p**m* − 1*e*},
|*S**p*1 ∩ ⋯ ∩ *S**p**m*| = ⌊*n*/(*p*1*p**m*)⌋⋅(*p*1*p**m* − 1⋅(⌊*n*/(*p*1*p**m*)⌋ + 1) − 2)/2.

The sum has *C**n* nonzero terms, where *C* converges to some constant that’s probably 6⋅(1 − ln 2)/π2 ≈ 0.186544. The final result is then |*S*| + *n* − 1.

# Answer
> 2 votes
# NewStack, 5 bytes

Luckily, there's actually a built in.

```
Nᵢ;qΣ

```

## The breakdown:

```
Nᵢ       Add the first (user's input) natural numbers to the stack.
  ;      Perform the highest factor operator on whole stack.
   q     Pop bottom of stack.
    Σ    Sum stack.

```

**In actual English:**

Let's run an example for an input of 8.

`Nᵢ`: Make list of natural numbers from 1 though 8: `1, 2, 3, 4, 5, 6, 7, 8`

`;`: Compute the greatest factors: `1, 1, 1, 2, 1, 3, 1, 4`

`q`. Remove the first element: `1, 1, 2, 1, 3, 1, 4`

`Σ` And take the sum: `1+1+2+1+3+1+4` = `13`

# Answer
> 2 votes
# Java 8, ~~78~~ ~~74~~ 72 bytes

```
n->{int r=0,j;for(;n>1;n--)for(j=n;j-->1;)if(n%j<1){r+=j;j=0;}return r;}

```

Port of *@CarlosAlejo*'s C# answer.

Try it here.

**Old answer (78 bytes):**

```
n->{int r=0,i=1,j,k;for(;++i<=n;r+=k)for(j=1,k=1;++j<i;k=i%j<1?j:k);return r;}

```

Try it here.

**Explanation (of old answer):**

```
n->{                    // Method with integer parameter and integer return-type
  int r=0,              //  Result-integers
      i=1,j,k;          //  Some temp integers
  for(;++i<=n;          //  Loop (1) from 2 to `n` (inclusive)
      r+=k)             //    And add `k` to the result after every iteration
    for(j=1,k=1;++j<i;  //   Inner loop (2) from `2` to `i` (exclusive)
      k=i%j<1?j:k       //    If `i` is dividable by `j`, replace `k` with `j`
    );                  //   End of inner loop (2)
                        //  End of loop (2) (implicit / single-line body)
  return r;             //  Return result-integer
}                       // End of method

```

# Answer
> 2 votes
# Thunno 2 `-S`, 5 bytes

```
ı⁺FṫG

```

Try it online!

#### Explanation

```
ı⁺FṫG  # Implicit input
       # Decrement the input
ı      # Map over [1..input-1]:
 ⁺     #  Increment the number
  Fṫ   #  Push the proper divisors
    G  #  Maximum of this list
       # Sum the list
       # Implicit output

```

# Answer
> 2 votes
# Arturo, 32 bytes

```
$=>[∑map..2&=>[x:do factors&]]

```

Try it!

# Answer
> 1 votes
# Lua, 74 bytes

```
c=0 for i=2,...do for j=1,i-1 do t=i%j<1 and j or t end c=c+t end print(c)

```

Try it online!

# Answer
> 1 votes
# , 18 bytes

```
[:+/1}.&.q:@+}.@i.

```

Try it online!

# Answer
> 1 votes
# Stacked, 31 bytes

```
[2\|>[divisors:pop\MAX]map sum]

```

Try it online! (All testcases except for 1000, which exceeds the 60 second online time limit.)

## Explanation

```
[2\|>[divisors:pop\MAX]map sum]
 2\|>                               range from 2 to the input inclusive
     [                ]map          map this function over the range
      divisors                      get the divisors of the number (including the number)
              :pop\                 pop a number off the array and swap it with the array
                   MAX              gets the maximum value from the array
                           sum      sum's all the max's

```

# Answer
> 1 votes
# C (gcc), 53 bytes

```
x;s;f(n){for(s=0;n>1;--n){for(x=n;n%--x;);s+=x;}n=s;}

```

Try it online!

Comfortably an quickly passes all test cases.

# Answer
> 1 votes
# Perl 6, 36 bytes

```
{sum map {max grep $_%%*,^$_},2..$_}

```

Test it

## Expanded:

```
{
  sum
    map
    {
      max
        grep
        $_ %% *, # is the input to this block divisible by
        ^$_      # Range of possible divisors
    },
    2 .. $_
}

```

# Answer
> 1 votes
# Alice, 17 bytes

```
/o
\i@/&w!qB;?+]k

```

Try it online!

## Explanation

This is a standard format for a program which takes input as an integer, outputs an integer, and does everything else in cardinal mode.

The program tries to add up the highest proper divisor of every number from 0 to n. In the case of 0 and 1, the number added comes from the implicit zeros on the stack, so we don't have to bother skipping these cases.

```
i    Take input string (in ordinal mode)
&w   Implicitly convert into an integer, and push a return address n times.
     This starts the main loop, which will run a total of n+1 times.
!    Store the accumulator on the current tape cell.
q    Get the tape position. (initially zero)
B    Compute all divisors.
;    Remove the top of the stack (the number itself).
?    Copy accumulator back from tape.
+    Add to greatest proper divisor.
]    Move tape right.
k    Return to pushed return address.  The (n+1)st time through this loop,
     there is nowhere to return to, and the program continues.
o    Output the integer (as a string in ordinal mode).
@    Terminate.

```

# Answer
> 1 votes
# Neim, 7 bytes

```
Γ)

```

Explanation:

```
Example input: 6
        Inclusive range [1 .. input]
         stack: [1 2 3 4 5 6]
 Γ       For each...
          Get factors
           stack: [[1] [1 2] [1 3] [1 2 4] [1 5] [1 2 3 6]]
          Remove last element
           stack: [[] [1] [1] [1 2] [1] [1 2 3]]
          Get greatest element
           stack: [0 1 1 2 1 3]
      )  End for each
        Sum.
         stack: [8]
Implicit output: 8

```

Try it!

# Answer
> 1 votes
# APL (Dyalog Unicode), 25 bytes

Lack of builtins is sad.

```
+/((⌈/∘⍸0=g|⊢)¨1+g←⍳1-⍨⊢)

```

Alternative dfn version: `{+/{⌈/⍸0=⍵|⍨⍳1-⍨⍵}¨1+⍳1-⍨⍵}`

Explanation:

```
+/((⌈/∘⍸0=g|⊢)¨1+g←⍳1-⍨⊢)
                 g←⍳1-⍨⊢   ⍝ numbers from 1 to ⍵-1 - define as `g`
               1+          ⍝ increment: numbers from 2 to ⍵.
              ¨            ⍝ for each of these...
        0=g|⊢              ⍝ mark evenly divisible indexes with 1
    ⌈/∘⍸                   ⍝ pick largest of proper divisors
+/                         ⍝ sum all

```

Try it online!

# Answer
> 1 votes
# K (ngn/k), ~~21~~ 20 bytes

```
+/{|/&~1!x%!x}'2_!1+

```

Try it online!

* `2_!1+` generate integers in range 2..x
* `{|/&~1!x%!x}'` get largest divisor for each value in generated range
* `+/` take the sum

# Answer
> 1 votes
# Perl 5 `-MList::Util=max -p`, 42 bytes

```
//,$\+=max grep$'%$_==0,1..$_-1for 2..$_}{

```

Try it online!

# Answer
> 1 votes
# Vyxal `s`, 27 bitsv2, 3.375 bytes

```
ƛKṪt

```

Try it Online!

## Explained

```
ƛKṪt
ƛ     # To each number 1..n
 KṪ   # Push the divisors of each number with that number removed
   t  # And get the last divisor remaining. Returns 0 on an empty list

```

Created with the help of Luminespire.

# Answer
> 0 votes
# Charcoal, 22 bytes

```
ＩＬ⪫Ｅ…·²Ｎ×⌈Ｅ…¹ι⎇﹪ιλ⁰λ1ω

```

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

```
      ²                 Literal 2
       Ｎ                Input number
    …·                  Inclusive range
   Ｅ                    Map with variable `i`
            ¹           Literal 1
             ι          Variable `i`
           …            Exclusive range
          Ｅ             Map with variable `l`
                ι       Variable `i`
                 λ      Variable `l`
               ﹪        Modulo
              ⎇         Ternary
                  ⁰     If nonzero then zero
                   λ    If zero then variable `l`
         ⌈              Take the maximum
                    1   Arbitrary character
        ×               Repeat it
  ⪫                  ω  Join the strings together
 Ｌ                      Take the length
Ｉ                       Cast to string
                        Implicitly print

```

The `Sum` function has been added since the question was asked, reducing the code to 18 bytes:

```
ＩΣＥ…·²Ｎ⌈Ｅ…¹ι⎇﹪ιλ⁰λ

```

# Answer
> 0 votes
# , 53 bytes

```
function(n){for(i in 2:n)F=F+(y=(i-1):1)[!i%%y][1]
F}

```

Try it online!

For each integer `i` in `2...n`, computes the divisors of `i` in decreasing order with `(y=(i-1):1)[!i%%y]` and then selects the first, as that will be the largest, adding it to `F`, which is by default initialized to `FALSE` or `0`.

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


title: Hashers and Crashers (Robbers)

text:
# Question
Title: Hashers and Crashers (Robbers)
*This is the robbers thread of this cops and robbers challenge. The cops thread is here*.

Related, but hashes numbers instead of strings and uses a different scoring system.

## Definitions

A hash collision is when two different strings produce the same hash.

## Summary

In this challenge, the cops will make a hash function, with a collision they know of. Then, the robbers will try to crack it by finding a hash collision in the cop's hash algorithm. To crack an answer, the hash collision the robber finds does not have to be the intended solution.

If a cop submission is not cracked for 7 days, it is safe, so mark it as such and reveal the intended crack and the score.
If a cop submission is cracked, mark it as such and edit in a link to the crack.

## Format

A robber answer has to contain **the hash collision, a link to the cracked answer, and the score**.

## Scoring

The score of a robber answer is **the sum of the number of bytes of the two strings with the hash collision, with the *higher* score being better**.

## The winner

With robbers and cops being ranked separately, the winner is the person with the best scoring answer.

## Example

Cop:

> ### Python
>
> ```
> from hashlib import*
> def singlecharhash(x):
>   a = blake2b(digest_size=1)
>   a.update(x)
>   return a.hexdigest()
>
> ```

Robber:

> ### 4 Points, Cracks cop's answer
>
> `¯` and `É`, both 2 bytes.

## Pinboard

I am thinking of changing the scoring system to make it the minimum of the two strings. Any thoughts?

# Answer
> 5 votes
# Cracks Sisyphus's, 1 byte

`b''` and `b'\x00'`

Try it online!

I'm not sure if this is the intended solution but it's definitely the simplest.

As @gsitcia has pointed out in the comments, for SHA-256 if the key is less than 64 bytes HMAC pads it with null bytes to length 64. So by adding a null byte to any key with less than 64 bytes we get the same result.

As @gsitcia also points out, for any key longer than 64 bytes, it is replaced with its hash. We can see this in action here. It is trivial to generate arbitrarily long collisions in this way.

---
Tags: cops-and-robbers, hashing
---