title: How can I get a repdigit?

text:
# Question
Title: How can I get a repdigit?
In honor of how much rep I had several hours ago, when I first thought of this challenge:

Numbers like this that are made up of a single digit repeating are called repdigits. Repdigits are fun! Every body would be more happy if the amount of rep they had was a repdigit, but I am impatient, so you need to help me find out the fastest way to get to a repdigit.

Here is your challenge:

Given a positive integers representing reputation, output the minimum amount of rep they need to *gain* to get to a repdigit. For example, at the time of writing this challenge, user Martin Ender had 102,856 rep. The nearest rep-digit is 111,111, so he would need to gain: 8255 rep to be at a repdigit.

Since people dislike losing rep, we will only consider non-negative changes. This means that, for example, if someone is at 12 rep, rather than losing 1 rep, the solution is to gain 10 rep. This allows '0' to be a valid output, since anyone who has 111 rep is *already* at a repdigit.

Input and output can be in any reasonable format, and since it is impossible to have less than 1 rep on any Stack Exchange site, you can assume no inputs will be less than 1.

One cornercase to note:

If a user has less than 10 rep, they are already at a repdigit, and so they also need '0'.

# Test IO:

```
#Input      #Ouput
8           0
100         11
113         109
87654321    1234567
42          2
20000       2222
11132       11090

```

Standard loopholes apply, and the shortest solution in bytes wins!

# Answer
> 9 votes
# Jelly, 6 bytes

```
DE$1#_

```

Output is a singleton array.

Try it online! or verify most test cases. Test case **87654321** is too slow for TIO.

### How it works

```
DE$1#_  Main link. Argument: n

   1#   Call the link to the left with argument k = n, n + 1, n + 2, etc. until one
        match is found, then return the matching k.
  $       Combine the two links to the left into a monadic chain.
D           Convert k to base 10.
 E          Test if all decimal digits are equal.
     _  Subtract n from the result.

```

# Answer
> 16 votes
# Haskell, 39 bytes

```
until(((==).head>>=all).show)(+1)>>=(-)

```

Try it online

# Answer
> 14 votes
# Brachylog, 9 bytes

```
:.#++#==,

```

Try it online!

This is pretty efficent as it makes use of constraints arithmetic.

### Explanation

```
:.            The list [Input, Output].
  #+          Both elements must be positive or zero.
    +         The sum of those two elements…
     #=       …must result in an integer where all digits are the same.
       =,     Assign a value that matches those constraints.

```

# Answer
> 10 votes
# Python 2, ~~41~~ 40 bytes

```
def f(n):r=10**len(`n`)/9;print-n/r*-r-n

```

Not the shortest approach, but very efficient. Test it on Ideone.

### How it works

For input `10**len(`n`)` rounds **n** up to the nearest power of **10**. Afterwards, we divide the result by **9**. This returns the repdigit **1…1** that has as many digits as **n**. We save the result in **r**. For example, if **n = 87654321**, then **r = 11111111**.

The desired repdigit will be a multiple or **r**. To decide which, we perform ceiling division of **n** by **r**. Since Python 2's division operator `/` floors, this can be achieved with `-n/r`, which will yield the correct absolute value, with negative sign. For example, if **n = 87654321**, this will return **-8**.

Finally, we multiply the computed quotient by **-r** to repeat the quotient once for each digit in **n**. For example, if **n = 87654321**, this returns **88888888**, which is the desired repdigit.

Finally, to calculate the required increment, we subtract **n** from the previous result. For our example **n = 87654321**, this returns **1234567**, as desired.

# Answer
> 9 votes
# Python 2, 37 bytes

```
f=lambda n:1-len(set(`n`))and-~f(n+1)

```

Test it on Ideone. Note that this approach is too inefficient for test case **87654321**.

### How it works

If **n** is already a repdigit, `1-len(set(`n`))` will return **0** since the length of the set of **n**'s digits in base 10 will be **1**. In this case, **f** returns **0**.

If **n** is not a repdigit, `f(n+1)` recursively calls **f** with the next possible value of **n**. `-~` increments the return value of **f** (**0** when a repdigit is found) by **1** each time **f** is called recursively, so the final return value equals the number of times **f** has been called, i.e., the number of times **n** had to be incremented to get a repdigit.

# Answer
> 8 votes
# Perl 6, 23 bytes

```
{($_...{[==] .comb})-1}

```

A lambda that takes the input number as argument, and returns the result.

Explanation:

1. Uses the `...` sequence operator to increment the input number until it reaches a repdigit *(tested by splitting its string representation into characters and seeing if they're all equal)*.
2. Subtracts one from the length of the sequence.

# Answer
> 7 votes
# Java 7, ~~116~~ 76 bytes

```
int c(int i){int r=(int)Math.pow(10,(i+"").length())/9;return(-i/r-1)*-r-i;}

```

Used *@Dennis*' amazing approach to lower the byte-count by a whopping 40 bytes.

**Ungolfed & test cases:**

Try it here.

```
class Main{
  static int c(int i){
    int r = (int)Math.pow(10, (i+"").length()) / 9;
    return (-i / r - 1) * -r - i;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(87654321));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(11132));
  }
}

```

**Output:**

```
0
11
109
1234567
2
2222
11090

```

# Answer
> 4 votes
# Pyth, ~~9~~ ~~8~~ 7 bytes

*1 byte thanks to @FryAmTheEggman.*

```
-f@F`TQ

```

Try it online.

Very inefficient, loops through all numbers from the input to the next repdigit.

# Answer
> 4 votes
# Brain-Flak ~~690~~ 358 bytes

Here's my go at it

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

```

Try It Online

### Explanation

Start by making a second copy of the input that is one less than the original. We will use the copy to search for the next repdigit. We subtract one in case the number itself was a repdigit

```
(({})[()])

```

Push one to satisfy the coming loop. (doesn't have to be one just not zero)

```
(())

```

This loop will run until there is a repdigit on top of the stack

```
{

```

Pop the crap. Their is a "boolean" on top that drives the loop, since it is no longer needed we pop it.

```
{}

```

Add one and duplicate the top. The copy will be decomposed into its digits.

```
(({}()))

```

While the copy is not zero...

```
{

```

Copy again

```
(({}))

```

Mod 10 and move to the other stack

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

```

Divide by 10 (Integer division)

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

}

```

Pop the zero that was our copy

```
{}

```

We have now decomposed the number into its base 10 digits, So we swap over to the stack with all the digits.

```
<>

```

While the leading digit is not zero

```
{

```

We pick up a copy of the stack height (i.e. the number of digits)...

```
(([])<

```

Silently subtract one from every number on the stack

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

```

Put the stack height we picked up down. (and swap to the other stack)

```
><>)

```

We use the stack height to pull all the digits we placed on the other stack back onto the proper stack.

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

```

Pop the zero that was our stack height

```
{}

```

Swap back onto the stack with the digits (or what were the digits)

```
<>

```

End loop

```
}

```

Now we have subtracted the top digit from all the other digits. If all the digits are zero the orginal number (not the input but the number we are checking) was a repdigit.<sup>\[citation needed\]</sup>. So we need to check for non-zeroes.

While the stack height is not zero

```
([])
{
{}

```

If the digit is not zero move it to the other stack and replace it with a zero.

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

```

Pop it (now it is a zero)

```
{}

```

End loop

```
([])
}
{}

```

Swap over onto the other stack (duh..)

```
<>

```

Grab our selves a copy of the stack height minus two

```
(([][()()])<

```

While the stack height is not two (the original and the accumulator)

```
{
{}

```

Pop the top

```
{}

```

End the while

```
([][()()])
}
{}

```

Put down our copy of the stack height minus two. This ends up being the number of digits that are not the same as the first digit. In other words if it is zero it is a repdigit.

```
>)

```

If this loop ends we have found a repdigit

```
}

```

Pop the "boolean"

```
{}

```

Subtract the original from the repdigit

```
({}[{}])

```

# Answer
> 3 votes
# Python 2, 52 bytes

```
a=b=input()
while len(set(str(a)))!=1:a+=1
print a-b

```

Python 2 has several tricks that make this shorter. For example, input is numeric, so we don't need to cast to int. (-5 bytes) We also don't need to put parenthesis around the `a-b` (-1 byte)

Use this script to verify all test cases:

```
def f(i):
    a=b=i
    while len(set(str(a)))!=1:a+=1
    return a-b

inputs = [8, 100, 113, 87654321, 42, 20000, 11132]
outputs = [0, 11, 109, 1234567, 2, 2222, 11090]

for i in range(len(inputs)):
    print(f(inputs[i]) == outputs[i])

```

You may also try it online!

# Answer
> 3 votes
## Excel, ~~85~~ 79 bytes

Put the following formula in any cell except cell `N` since it's a name for reference cell of input:

```
=IF(1*(REPT(LEFT(N),LEN(N)))<N,REPT(LEFT(N)+1,LEN(N))-N,REPT(LEFT(N),LEN(N))-N)

```

Explanation:

* `N` is the input and also name of reference cell.
* `LEFT(N)` take the first digit of input value.
* `LEN(N)` return the length of input value.
* `REPT(LEFT(N),LEN(N))` repeat the first digit of input value `LEN(N)` times and multiply it by 1 to convert text format to number format so we can use it for number comparison.
* The syntax for the IF function in Microsoft Excel is: **IF( condition, \[value\_if\_true\], \[value\_if\_false\])**, hence makes the whole formula is self-explanatory.

# Answer
> 3 votes
## GNU sed, 223 + 1(r flag) = 224 bytes

```
s/$/:0%/
:;y/:%/%:/
/^(.)\1*%/{s/.*%(.*):/\1/;q}
:f;s/9(@*:)/@\1/;tf
s/8(@*:)/9\1/;s/7(@*:)/8\1/
s/6(@*:)/7\1/;s/5(@*:)/6\1/
s/4(@*:)/5\1/;s/3(@*:)/4\1/
s/2(@*:)/3\1/;s/1(@*:)/2\1/
s/0(@*:)/1\1/;s/(^|%)(@*:)/\11\2/
y/@/0/;t

```

**Run:**

```
sed -rf repdigit.sed <<< "112"

```

**Output:**

```
110

```

This is a **pure sed solution**, the arithmetic is simulated using regular expressions only. The algorithm works as follows:

1. the pattern space format is set to `^current_reputation:needed_reputation%$`
2. in each iteration of the main loop the separators are switched:
a) `%:` applies the increment to *needed\_reputation*
b) `:%` applies the increment to *current\_reputation*
3. if the *current\_reputation* is a "repdigit", the *needed\_reputation* is printed and the program ends

# Answer
> 2 votes
# 05AB1E, ~~10~~ 6 bytes

```
∞.Δ+Ë

```

Try it online!

**Explanation**

```
∞<      # from the infinite list of non-negative integers
  .Δ    # find the first number where
     Ë  # all digits are equal
    +   # after adding the input

```

# Answer
> 2 votes
# R, ~~102~~ ~~98~~ 91 bytes

```
a=scan(,'');i=0;while(length(unique(strsplit(a,"")[[1]]))!=1){a=paste(strtoi(a)+1);i=i+1};i

```

**Ungolfed :**

```
a=scan(,'') #Asks for input
i=0         #Initialize i to 0, surprisingly

while(length(unique(strsplit(a,"")[[1]]))!=1)
    #Splits the input into its digits,
    #compute the length of the vector created by the function `unique`, which gives all the digits once.
    #as long as the this length is different from one :
{
a=paste(strtoi(a)+1) #Increases by one the value of the input (while messing around with its format)
i=i+1                           #Increases by one the value of the counter
}

i #Outputs the counter

```

Messing around with the format (~~`as.numeric` and `as.character`~~) adds some bytes, but **R** is not really flexible !

# Answer
> 2 votes
## PowerShell v2+, 66 bytes

```
param($n)for($x=+"$($n[0])";($y="$x"*$n.length)-lt$n;$x++){}+$y-$n

```

The usually-good-for-golf very loose casting of PowerShell is a major downfall here.

Takes input `$n` as a string, and enters a `for` loop. For the setup step, we extract out the first character `$n[0]`, but have to convert it back to a string `"$(...)"` before casting as an int `+` and saving into `$x`. Otherwise, the later arithmetic will be using the ASCII value of the char-code.

The conditional checks whether a string constructed from `$n.length` `"$x"`s, temporarily stored in `$y`, is less-than `$n`. So long as it's not, we increment `$x++`, setting up the conditional for the next loop.

For example, for input `123`, the value of `$y` when the conditional is first checked will be `111`, which is less-than `$n`, so the loop continues. There's nothing in the loop body, so the step increment happens `$x++`, then the conditional is checked again. This time `$y` equals `222`, which is greater than `$n`, so the loop terminates. If the input is already a repdigit, the conditional is not satisfied, because at that point `$y` is equal to `$n`.

Once out of the loop, we cast `$y` to an integer `+`, then subtract `$n`. That result is left on the pipeline and output is implicit.

# Answer
> 2 votes
## Perl, 40 + 1 (`-n`) = 41 bytes

```
/^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo

```

If printing nothing instead of `0` when the number is already a repdigit is acceptable, then 37 bytes are enough :

```
/^(.)\1*$/&&say$v or$_++&&++$v&&redo

```

Run with `-n` (1 byte) and `-E` or `-M5.010` (free) :

```
perl -nE '/^(.)\1*$/&&say($v|0) or$_++&&++$v&&redo'

```

**Explanations** : there are two major parts in the code : `/^(.)\1*$/&&say$v` and `$_++&&++$v&&redo`. The first one test if `$_` is a repdigit; if yes it prints the number we added to the original number to make it a repdigit (`$v`), and if no, we had 1 to both `$_` and `$v`, and start over.

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

```
int c(int i){int n=0;while(!(i+++"").matches("^(.)\\1*$"))n++;return n;}

```

*(If the other Java entry is 76 bytes, this one is ~~74~~ 72, since it's ~~two~~ four bytes shorter).*

Anyway, just increment the input until it's a repdigit while incrementing a counter. Return the counter.

Yes, those are three pluses in a row, two to increment the input, one to concatenate an empty string to make it a string.
No, I didn't think it would be legal without a space in between either, but there you go. That's what a typo will do for you: one byte shorter.

Using a for-loop instead of a while takes exactly as many bytes:

```
int c(int i){int n=0;for(;!(i+++"").matches("^(.)\\1*$");n++);return n;}

```

---

## *Edit:*

*An earlier version had `matches("^(\\d)\\1*$")` to check for a repdigit, but since we've just converted an int to a string, using a `.` to match is enough.*

---

**Ungolfed & test cases:**

Try it here.

```
class Main{
  static int c(int i){
    int n=0;
    while(!(i++ + "").matches("^(.)\\1*$")) {
      n++;
    }
    return n;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(87654321));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(11132));
  }

```

}

**Output:**

```
0
11
109
1234567
2
2222
11090

```

# Answer
> 2 votes
# Vyxal, 6 bytes

```
λ?+≈;ṅ

```

Try it Online!

# Answer
> 1 votes
## Pyke, ~~13~~ 11 bytes

```
o+`}ltIr)ot

```

Try it here!

```
            - o = 0
o+          -     o++ + input
  `         -    str(^)
   }        -   deduplicate(^)
    lt      -  len(^)-1
      I )   - if ^:
       r    -  goto_start()
         ot - o++ -1

```

# Answer
> 1 votes
## Actually, 15 bytes

```
;D;WXu;$╔l1<WX-

```

Try it online!

Explanation:

```
;D;WXu;$╔l1<WX-
;                dupe
 D;              decrement, dupe
   WXu;$╔l1<W    while top of stack is truthy:
    X              discard
     u             increment
      ;            dupe
       $╔l1<       1 if len(str(TOS)) > 1 else 0 (check if the string representation of the TOS contains only one unique digit)
                 after the loop, the stack will be [1 repdigit input]
             X   discard
              -  subtract input from repdigit

```

# Answer
> 1 votes
## JavaScript (ES6), 42 bytes

```
f=(n,p=1)=>n<p?-~(n*9/p)*~-p/9-n:f(n,p*10)

```

Explanation: Recursively computes `p` as the next power of `10` after `n`. The digit to be repeated is then computed as `1+floor(9n/p)`, and the repunit is simply `(p-1)/9`, from which the result follows.

# Answer
> 1 votes
## Jellyfish, 20 bytes

```
p
<
)\&&&~j<i
->N>u0

```

Try it online! TIO can't handle the longer test cases, but given enough time and memory, they should work too.

## Explanation

* `i` is input, and `<` decrements it. This value is fed to the function on the left.
* `\>` increments the value (at least once) until the function to the right gives a truthy value.
* The test function is a composition (by `&`s) of four functions.
* `0~j` converts to string.
* `u` removes duplicate digits.
* `>` removes the head of the resulting string.
* `N` is logical negation: it gives `1` for an empty string, and `0` for non-empty. Thus the function tests for a rep-digit, and the result of `\` is the next rep-digit counting from `<i`.
* `)-` subtracts the result from the function input, that is, `<i`.
* This difference is off by one, so `<` decrements it. Finally, `p` prints the result.

# Answer
> 1 votes
# MATL, 10 bytes

```
q`QtVda}G-

```

Try it online!

This keeps incrementing the input until all digits are equal, so it's slow. The test case for input `87654321` times out in the online compiler.

```
q      % Take input implicitly. Subtract 1
`      % Do...while loop
  Q    %   Increment top of the stack
  tV   %   Duplicate and convert to string (i.e. digits of the number)
  d    %   Difference between consecutive digits
  a    %   True if any such difference is nonzero. This is the loop condition
}      % Finally (execute on loop exit)
  G-   %   Subtract input. This is the final result, to be (implicitly) displayed
       % End loop implicitly. If loop condition (top of the stack) is truthy: proceeds
       % with next iteration. Else: executes the "finally" block and exits loop
       % Display implicitly

```

# Answer
> 1 votes
# PHP 5.6, ~~59~~ ~~53~~ ~~51~~ 50 bytes

Saved ~~6~~ 8 bytes thanks to @manatwork.

```
while(count_chars($argv[1]+$b,3)[1])$b++;echo$b?:0

```

Test with:

```
php test.php 11132

```

The `count_chars()` function with 3 as the second parameter returns a string with the distinct characters in a string. When this string is 1 character long (`[1]` will return false when it's length 1) then echo `$b`, otherwise increment `$b` and loop again.

# Answer
> 1 votes
## Matlab, ~~65~~ 64 bytes

```
t=input('');i=0;while nnz(diff(+num2str(t+i)))
i=i+1;end
disp(i)

```

Because of the while loop it's rather slow...

**Explanation**

```
t=input('')  -- takes input
i=0          -- set counter to 0
while
          num2str(t+i)   -- convert number to string
         +               -- and then to array of corresponding ASCII codes
    diff(             )  -- produce vector of differences (all zeros for 'repdigit')
nnz(                   ) -- and count non-zero entries
i=i+1                    -- while not all digits are the same increase the counter
end          -- end while loop
disp(i)      -- print the counter

```

*Saving one byte thanks to @Luis Mendo.*

# Answer
> 1 votes
# Java, 59 bytes

```
int c(int i){return(i+"").matches("^(.)\\1*$")?0:c(i+1)+1;}

```

*(I'm still not sure how to count Java entries, but according to the standard set by the first Java entry, this entry is 59 bytes, since it's 17 bytes shorter).*

Anyway, if we have a repdigit, return 0, else add 1 to the input, call itself and add 1 to the result.

---

**Ungolfed & test cases:**

Try it here.

```
class Main{
  static int c(int i) {
    return
      (i+"").matches("^(.)\\1*$")
      ? 0
      : c(i+1) + 1;
  }

  public static void main(String[] a){
    System.out.println(c(8));
    System.out.println(c(100));
    System.out.println(c(113));
    System.out.println(c(42));
    System.out.println(c(20000));
    System.out.println(c(19122));
    // Entry below will run out of memory
    System.out.println(c(19121));
  }
}

```

**Output:**

```
Runtime error   time: 0.09 memory: 321152 signal:-1
0
11
109
2
2222
3100

```

As you can see, the last entry runs out of memory before it can finish. The (very appropriate) `StackOverflowError` is thrown from `java.util.regex.Pattern.sequence(Pattern.java:2134)`, but I'm pretty confident there's nothing wrong with the regex itself, since it's the same one I used in my previous entry.

# Answer
> 1 votes
# Ruby, 42 characters

```
->n{i=0;n.next!&&i+=1while n.squeeze[1];i}

```

Expects string input.

Sample run:

```
irb(main):019:0> ->n{i=0;n.next!&&i+=1while n.squeeze[1];i}['87654321']
=> 1234567

```

## Ruby, 39 characters

Recursive call, runs into “SystemStackError: stack level too deep” on bigger results.

```
r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i}

```

Sample run:

```
irb(main):001:0> r=->n,i=0{n.squeeze[1]?r[n.next,i+1]:i}
=> #<Proc:0x00000002367ca0@(irb):10 (lambda)>

irb(main):002:0> r['20000']
=> 2222

```

# Answer
> 1 votes
## Prolog, 120 bytes

```
r([H|T]):-r(H,[H|T]).
r(H,[H|T]):-r(H,T).
r(_,[]).
g(N,0):-number_chars(N,L),r(L).
g(N,X):-N1 is N+1,g(N1,X1),X is X1+1.

```

Try it online!

# Answer
> 1 votes
# Brachylog v2, 6 bytes

```
;.+=∧ℕ

```

Try it online!

```
  +       The sum of
          the input
;         and
 .        the output
   =      is a repdigit,
    ∧     and
          the output
     ℕ    is a whole number.

```

The 5-byte `+↙.=∧` gets away with omitting  because it doesn't try non-positive outputs at all, but it also fails when given a number which is already a repdigit because it doesn't try non-positive outputs at all.

# Answer
> 1 votes
# Forth (gforth), 54 bytes

```
: f 0 over s>f flog f>s 1+ 0 do 10 * 1- loop mod abs ;

```

Try it online!

### Explanation

* Gets the smallest repdigit of the same length as the input.
* Negates the result and gets the remainder of dividing the input by that number.
* Returns the absolute value of the result (since positive modulo negative is negative)

### Code Explanation

```
: f                \ start a new word definition
  0 over           \ place 0 on stack and copy input back to top
  s>f flog f>s     \ move number to floating point stack, get log10, move back to stack (truncate)
  1+               \ add 1 to get number of digits
  0 do             \ start a loop from 0 to number of digits - 1
    10 * 1-        \ repeatedly multiply by 10 and subtract 1 to get smallest repdigit of that size
  loop             \ end loop
  mod abs          \ get that absolute value of input modulo result
;                  \ end the word definition

```

# Answer
> 1 votes
# Rockstar, 122 bytes

```
listen to N
let M be N-1
O's 0
until O
let M be+1
cut M in S
roll S in D
O's 1
while S and O
let O be D's roll S

say M-N

```

Try it (Code will need to be pasted in)

# Answer
> 0 votes
## C#, 82 bytes

```
using System.Linq;n=>{int i=n;while((i+"").Distinct().Count()!=1)++i;return i-n;};

```

# Answer
> 0 votes
# C, 84 bytes

```
d,n,l,f;F(i){for(n=0;1;){l=i+n++;d=l%10;f=0;while(l/=10)f|=l%10-d;if(!f)return--n;}}

```

Test main:

```
int main() {
  printf("%d\n", F(8));
  printf("%d\n", F(100));
  printf("%d\n", F(113));
  printf("%d\n", F(87654321));
  printf("%d\n", F(47));
  printf("%d\n", F(20000));
  printf("%d\n", F(11132));
}

```

# Answer
> 0 votes
# J, 39 bytes

```
f=.$:&>:`[@.(1=#@~.@(10&#.inv)@])
g=.0&f

```

Take the digits `(10&#.inv)@]`, remove dups `~.`, check if the length is 1 (same basic idea as Dennis's solution). Recurse with incremented left and right args if it's not.

Note because `$:` recurses on the *entire* verb, we need to define a second verb to give the left arg an initial value of 0. I'd be curious to know how to avoid that, if possible.

Also, I'd be curious to know if there is a way to do this with `^:` (do... while version).

Try it online!

# Answer
> 0 votes
# TI-BASIC, 51 bytes

```
Ans→A:Ans→B:Repeat dim(Ans)=sum(Ans(1)=Ans:B+1→B:int(10fPart(B₁₀^(seq(⁻X-1,X,0,log(B:End:B-A

```

Slowly iterates through all integers greater than the input until the next repdigit has been reached.
Checks \\$\approx20\\$ numbers per second.

Input is the current reputation in `Ans`.
Output is the amount of rep required to reach the next repdigit.

**Examples:**

```
100
             100
prgmCDGF1D
              11
11132
           11132
prgmCDGF1D
           11090

```

Test case `11132` took \\$\approx9.5\\$ minutes to run.

**Explanation:**

```
Ans→A                                ;store the input into A and B
Ans→B
Repeat dim(Ans)=sum(Ans(1)=Ans       ;"do-while" the digits of B are not equal
B+1→B                                ;increment B
int(10fPart(B₁₀^(seq(⁻X-1,X,0,log(B  ;generate a list of B's digits reversed.  leave it in Ans
End
B-A                                  ;calculate the rep needed.  leave the result in Ans
                                     ;implicit print of Ans

```

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.

# Answer
> 0 votes
# Thunno 2, 5 bytes

```
µƘạ;_

```

Try it online!

#### Explanation

```
µƘạ;_  # Implicit input
µƘ ;   # Starting from the input, find the first integer where:
  ạ    #  Its digits are all equal (i.e. it's a repdigit)
    _  # Subtract the input from this number
       # Implicit output

```

# Answer
> 0 votes
# Desmos, 70 bytes

Ported from @Anastasiya-Romanova 秀's Excel solution.

```
d=floor(logn)
a=floor(n/10^d)
r=∑_{i=0}^d10^i
f(n)=(a+\{ar<n,0\})r-n

```

Try it on Desmos!

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


title: Disarium Dilemma

text:
# Question
Title: Disarium Dilemma
## Disarium Dilemma

A Disarium is defined as a number whose:

> sum of its digits powered with their respective position is equal to the original number

---

**Your Task**:

You have a strange obsession with numbers classified as being a disarium. The need to follow the ways of disarium is so great in you that you **refuse** to read any non-disarium numbered pages in any given book. You have two **BIG** problems:

1. Your professor just assigned you to read your textbook from page `n` to page `m`
2. You hit your head really hard last week and can't seem to remember how to programmatically determine if a number is considered to be a disarium.

Time is of the essence so the code to determine the pages you will need to read needs to be as short as possible.

You need to identify all of the disarium within an inclusive range of `n` through `m`.

**Examples of a disarium**:

> 89 = 81 \+ 92
>
> 135 = 11 \+ 32 \+ 53
>
> 518 = 51 \+ 12 \+ 83

This is code-golf, so the least number of bytes wins!

Here is the full sequence of A032799.

# Answer
> 11 votes
# Perl 6, ~~40~~ 39 bytes

```
{grep {$_==sum .comb Z**1..*},$^a..$^b}

```

Try it online!

### How it works

```
{                                     }  # A lambda.
                              $^a..$^b   # Range between the two lambda arguments.
 grep {                     },           # Return numbers from that range which satisfy:
               .comb Z  1..*             #  Digits zipped with the sequence 1,2,3,...,
                      **                 #  with exponentiation operator applied to each pair,
           sum                           #  and those exponents summed,
       $_==                              #  equals the number.

```

# Answer
> 8 votes
# Python2, ~~98~~ ~~89~~ ~~88~~ 84 bytes

```
lambda n,m:[x for x in range(n,m+1)if sum(int(m)**-~p for p,m in enumerate(`x`))==x]

```

~~Horrible. Will get shorter.~~ Starting to look better

Here's my recursive attempt (86 bytes):

```
f=lambda n,m:[]if n>m else[n]*(sum(int(m)**-~p for p,m in enumerate(`n`))==n)+f(n+1,m)

```

Thanks to @Rod for saving 4 bytes! `range` to `enumerate` and so on.

# Answer
> 7 votes
# JavaScript (ES7), ~~105~~ ~~91~~ ~~89~~ ~~88~~ ~~83~~ ~~79~~ ~~82~~ 81 bytes

*Thanks to Arnauld for saving 20B, and ETHProductions for saving 6B!*

```
a=>b=>[...Array(b).keys()].filter(c=>c>=a&([...c+''].map(d=>c-=d**++e,e=0),!c))

```

## Usage

Assign the function to a variable, and give it the minimum and the maximum as arguments. Example:

```
f=a=>b=>[...Array(b).keys()].filter(c=>c>=a&([...c+''].map(d=>c-=d**++e,e=0),!c))
f(0)(90)

```

### Output

```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

```

## Further golfing

This seems pretty well-golfed, but there's always room for improvement... I think.

# Answer
> 6 votes
# Python 3, 100 bytes

```
lambda n,m:{*range(10),89,135,175,518,598,1306,1676,2427,2646798,0xa8b8cd06890f2773}&{*range(n,m+1)}

```

Not the shortest approach, but a pretty cute one. There are finitely many disariums; see the OEIS page for a nice proof. These are all of them.

# Answer
> 6 votes
# 05AB1E, 12 bytes

Saved 2 bytes thanks to Emigna

```
ŸvygLySmOyQ—

```

Try it online!

```
Ÿ            # push [a .. b]
 vy          # for each
   gL        # push [1 .. num digits]
     yS      # push [individual digits]
       m     # push [list of digits to the power of [1..num digits] ]
        O    # sum
         yQ— # print this value if equal

```

# Answer
> 6 votes
# JavaScript (Firefox 52+), 68 bytes

```
f=(n,m)=>(e=0,[for(d of t=n+'')t-=d**++e],t||alert(n),n-m&&f(n+1,m))

```

Recursive function that outputs via `alert`. Works in the Developer Edition of Firefox, which you can download on this page. Previous versions of Firefox don't support the `**` operator, and no other browser supports `[for(a of b)c]` syntax.

### Test snippet

This uses `.map` instead of an array comprehension, and `Math.pow` instead of `**`, so it should work in all browsers that support ES6.

```
f=(n,m)=>(e=0,[...t=n+''].map(d=>t-=Math.pow(d,++e)),t||alert(n),n-m&&f(n+1,m))

f(0,100)
```

# Answer
> 6 votes
# Perl, 43 bytes

```
map{say if$_==eval s/./+$&**$+[0]/gr}<>..<>

```

Try it online!

Regex is really powerful, you guys.

## Explanation

The first thing the code does is read two integers as input via `<>`, and creates a range from the first to the second with `..`. It then uses the standard `map` function to iterate through this range, and applies the following code to each value: `say if$_==eval s/./+$&**$+[0]/gr`. This looks like gibberish, and it kind of is, but here's what's really happening.

`map` implicitly stores its current value in the variable `$_`. Many perl functions and operations use this value when none is given. This includes regular expressions, such as the `s///` substitution operator.

There are four parts to a substitution regex:

1. String to be manipulated. Ordinarily, the operator `=~` is used to apply a regex to a string, but if this operator is absent, then the regex is applied to the implicit variable `$_`, which contains our current number via the `map` function.
2. String to search for. In this case, we're searching for any single non-newline character, denoted by the wildcard `.`. In effect, we're capturing each individual digit.
3. String to replace with. We're substituting a plus sign `+` followed by a mathematical expression, mixed in with some magical Perl variables that make everything significantly easier.

The special scalar variable `$&` always contains the entirety of the last successful regex capture, which in this case is a single digit. The special array variable `@+` always contains a list of *postmatch offsets* for the last successful match, i.e. the index of the text *after* the match. `$+[0]` is the index in `$_` of the text immediately following `$&`. In the case of `135`, we capture the digit `1`, and the index in `135` of the text immediately afterwards (namely, `35`) is 1, which is our exponent. So, we want to raise `$&` (1) to the power of `$+[0]` (1) and get 1. We want to raise 3 to the power of 2 and get 9. We want to raise 5 to the power of 3 and get 125.

If the input was `135`, the resulting string is `+1**1+3**2+5**3`.

4. Regex-modifying flags. Here we're using two regex flags -- `/g` and `/r`. `/g` tells the interpreter to continue replacements after the first is found (otherwise we'd end up with `+1**135`). `/r` tells the interpreter *not to modify the original string*, and instead return what the string would be after the replacements. This is important, because otherwise, it would overwrite `$_`, and we need it for comparison purposes.

Once the entire substitution is done, we get a mathematical expression, which is evaluated with the `eval` function. `+1**1+3**2+5**3` is evaluated into `1 + 9 + 125 = 135`, which is compared to the original number `135`. Since these two are equal, the code prints the number.

# Answer
> 4 votes
# Jelly, 11 bytes

```
D*J$S⁼
rÇÐf

```

Try it online!

Got this down from 16 to 11, with some help from @miles!

Explanation:

```
rÇÐf    Main link, arguments are m and n
r       Generate a list from m to n
 Ç      Invoke the helper link
  Ðf    And filter out all that don't return 1 on that link

D*J$S⁼  Helper link, determines if item is Disarium
D       Break input (the current item of our list in Main) into digits (135 --> [1, 3, 5])
  J$    Create a range from 1 to x, where x is the number of digits             [1, 2, 3]
 *      Raise each digit to the power of their respective index
    S⁼  And return a 1 if the sum of powers is equal to the helper-link's input

```

# Answer
> 4 votes
## R, 100 bytes

```
function(n,m,x=n:m)x[sapply(x,function(y)sum(as.integer(el(strsplit(c(y,""),"")))^(1:nchar(y)))==y)]

```

Unnamed function that takes `n` and `m`. As always in R, splitting integers into a numeric digit vector is tedious and eats up a lot of bytes. This makes the function relatively slow and only works for 32-bit integers.

# Answer
> 3 votes
# CJam, 23 bytes

```
q~),\>{_Ab_,,:).#:+=},p

```

Try it online!

**Explanation**

```
q~                      Get and eval all input
  ),\>                  Get the range between m and n, inclusive
      {                 For each number in the range...
       _Ab               Duplicate and get the list of digits
          _,,:)          Duplicate the list, take its length, make the range from 1 to length
               .#        Vectorize with exponentiation; computes first digit^1, second^2, etc
                 :+      Sum the results
                   =     Compare to the original number
                    },  Filter the range to only numbers for which the above block is true
                      p Print nicely

```

# Answer
> 3 votes
# 05AB1E, 18 bytes

```
Ÿvy©SDgLsmO®Qi®}})

```

Try it online!

# Answer
> 3 votes
# Python 2.X, 92 bytes

```
lambda m,n:[k for k in range(m,n+1)if sum(int(j)**(i+1) for i,j in enumerate(list(`k`)))==k]

```

# Answer
> 3 votes
# Python 2, 84 bytes

A full program approach, currently the same length as the lambda solution.

```
a,b=input()
while a<=b:
 t=p=0
 for x in`a`:p+=1;t+=int(x)**p
 if t==a:print a
 a+=1

```

**Try it online!**

# Answer
> 3 votes
# Japt, 15 bytes

```
òV f_¥Zì £XpYÄÃx

```

Test it online! This was a collaboration between @obarakon and myself.

### How it works

```
òV f_¥Zì £XpYÄÃx   // Implicit: U, V = input integers
òV                 // Create the inclusive range [U...V].
   f_              // Filter to only the items Z where...
               x   //   the sum of
      Zì           //   the decimal digits of Z,
         £XpYÄÃ    //   where each is raised to the power of (index + 1),
     ¥             //   is equal to Z.
                   // Implicit: output result of last expression

```

In the latest version of Japt, `x` accepts a function as an argument, which allows us to golf another byte:

```
òV f_¥Zì x@XpYÄ

```

Test it online!

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
ŸʒDSāmOQ

```

Try it online!

# Answer
> 2 votes
## Clojure, 107 bytes

```
#(for[i(range %(inc %2)):when(=(int(apply +(map(fn[i v](Math/pow(-(int v)48)(inc i)))(range)(str i))))i)]i)

```

Implementing the equation is terribly long.

# Answer
> 2 votes
# TI-Basic, 85 bytes

```
Input
For(I,X,Y
If I<=9 or sum(I={89,135,175,518,598,1306,1676,2427,2646798,12157692622039623539
Disp I
End

```

# Answer
> 2 votes
# PHP, ~~92~~ ~~91~~ 88 bytes

3 bytes saved thanks @AlexHowansky

```
for([,$n,$m]=$argv;$n<=$m;$s-$n++?:print"$s,")for($i=$s=0;_>$b=($n._)[$i++];)$s+=$b**$i;

```

takes input from command line arguments; prints a trailing comma. Run with `-r`.

# Answer
> 2 votes
## Haskell, 61 bytes

```
n#m=[i|i<-[n..m],i==sum(zipWith(^)(read.pure<$>show i)[1..])]

```

Usage example `5 # 600` -\> `[5,6,7,8,9,89,135,175,518,598]`.

Check each number `i` in the range `[n..m]`. The digits are extracted by turning `i` into a string (`show`) and making each char a one element string (`pure`) which is turned into an integer again (`read`). Zip those numbers element wise with `[1..]` via the function `^` and take the `sum`.

# Answer
> 2 votes
# Mathematica, 59 bytes

```
Select[Range@##,Tr[(d=IntegerDigits@#)^Range@Length@d]==#&]&

```

Unnamed function taking two integer arguments and returning a list of integers. `(d=IntegerDigits@#)^Range@Length@d` produces the list of digits of a number to the appropriate powers; `Tr[...]==#` detects whether the sum of those digit-powers equals the original number.

# Answer
> 2 votes
# **MATLAB, ~~88~~ 73 bytes**

```
@(n,m)find(arrayfun(@(n)n==sum((num2str(n)-48).^(1:log10(n)+1)),n:m))+n-1

```

Original answer:

```
function g(n,m);a=n:m;a(arrayfun(@(n)n==sum((num2str(n)-'0').^(1:floor(log10(n))+1)),a))

```

`num2str(n)-'0'` splits a `n` into a vector of its digits, and `1:floor(log10(n))+1` is a vector holding one to the number of digits in `n`. Thanks to log for the golf down to an anonymous function, saving 15 bytes.

# Answer
> 2 votes
# Japt, 12 bytes

```
òV fÈ¶ìxÈpYÄ

```

Try it

```
òV fÈ¶ìxÈpYÄ     :Implicit input of integers U & V
òV               :Range [U,V]
   f             :Filter by
    È            :Passing each through the following function
     ¶           :  Check for equality with
      ì          :  Convert to digit array
       x         :  Reduce by addition
        È        :  After passing each element at 0-based index Y through the following function
         p       :    Raise to the power of
          YÄ     :    Y+1

```

# Answer
> 2 votes
# Brachylog, 10 bytes

```
⟦₂∋.i₁ᶠ^ᵐ+

```

Try it online!

Generates each disarium through the output variable.

```
   .          The output variable is
  ∋           an element of
⟦₂            the inclusive range between the elements of the input.
      ᶠ       Find every
    i₁        pair of a digit and its 1-index in the output variable,
       ^ᵐ     and raise each digit to the power of its index.
         +    The sum is equal to the output variable.

```

Also worth mentioning here, rather than in a comment or its own submission, that steenbergh's Jelly solution can now be golfed down to `rD*J$S⁼ƲƇ`, but I might find this a bit more idiomatic:

# Jelly, 9 bytes

```
rD*J$SƊƑƇ

```

Try it online!

# Answer
> 2 votes
# Desmos, 82 bytes

```
a=[n...m]
d=\floor(\log a)
f(n,m)=a[a=\sum_{i=0}^d\mod(\floor(a/10^i),10)^{d-i+1}]

```

Try it on Desmos!

# Answer
> 1 votes
## Python 2, 100 bytes

```
for i in range(input(),input()+1):x=sum(int(`i`[n])**-~n for n in range(len(`i`)));print("",x)[x==i]

```

I haven't had a chance to run this yet (doing this on my phone).

# Answer
> 1 votes
# Haskell, ~~82 76~~ 75 bytes

```
n!m=[x|x<-[n..m],x==x#(length.show)x]
0#i=0
n#i=(div n 10)#(i-1)+mod n 10^i

```

Try it online! Usage: `5 ! 175`

This checks each number in the range `n` to `m` if its a disarium number and is hence quite slow for big `m`.

---

Faster version: (93 bytes)

```
n!m=[x|x<-[0..9]++[89,135,175,518,598,1306,1676,2427,2646798,12157692622039623539],x>=n,x<=m]

```

Try it online!

# Answer
> 1 votes
## C ~~175~~ 169 bytes

```
f(a,b){for(j=a;j<b;j++){n,i=0,x=0;s=0;n=j;while(n!=0){n/=10;i++;}a[i];n=j;while(n!=0){a[i-x-1]=n%10;n/=10;x++;}for(x=0;x<i;x++)s+=(int)pow(a[x],x+1);if(j==s)printf("%d ",s);}}

```

Ungolfed version:

```
void f(int a, int b)
{

  for(int j=a; j<b;j++)
  {
    int n,i=0,x=0;
    int s=0;
    n=j;

   //Convert each number from 'n' to 'm' and store it in an int array
   while(n)
   {
     n/=10;
     i++;
   }
   int a[i];

   n=j;
   while(n)
   {
    a[i-x-1]=n%10;
    n/=10;
    x++;
   }

  //Calculate sum of digits powered with their respective position
  for(x=0;x<i;x++)
   s+=(int)pow(a[x], x+1);

   //Print Desarium
   if(j==s)
    printf("%d ", sum);
 }

}

```

Can be shortened in some way, but I don't see it at the moment.

@TuukkaX Thanks for saving 6 bytes.

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

```
r[]={0,0};f(n){if(n)f(n/10),r[1]=pow((n%10),*r)+r[1]+.5,r[0]++;else*r=1,r[1]=0;}g(m,x){for(;m<=x;m++){f(m);if(m==r[1])printf("%d,",m);}}

```

Header defining pow on TIO because for some reason it didn't auto include pow. My computer did, so I'm going to roll with that.

Try it online!

# Answer
> 1 votes
# MATL, 16 bytes

```
&:"@tFYAtn:^s=?@

```

Try it online!

```
&:        % Input two n, m implicitly. Push array [n n+1 ... m]
"         % For each k in that array
  @       %   Push k
  tFYA    %   Duplicate. Convert to decimal digits
  tn:     %   Duplicate. Push [1 2 ... d], where d is the number of digits
  ^       %   Element-wise power
  s       %   Sum of array
  =       %   Compare with previous copy of k: is it equal?
  ?       %   If so
    @     %     Push k
          %   End, implicit
          % End, implicit
          % Display stack, implicit

```

# Answer
> 1 votes
# Octave, 88 87 bytes

*Thanks to MattWH for saving a byte (f(x)-48 vs f(x)-'0')*

```
@(n,m,f=@num2str,a=n:m)a(a==cell2mat(arrayfun(@(x){sum((f(x)-48).^(1:nnz(f(x))))},a)))

```

To run:

```
>> f=@(n,m,f=@num2str,a=n:m)a(a==cell2mat(arrayfun(@(x){sum((f(x)-'0').^(1:nnz(f(x))))},a)))
>> f(0,1000)
ans =
      1     2     3     4     5     6     7     8     9    89   135   175   518   598

```

## Explanation

```
@(n,m,                                              % Create an anonymous function and pass it n and m as paramteres
    f=@num2str,                                     % Will be using the num2str mehtod twice, set the variable f to the handle to save on bytes
        a=n:m)                                      % Create a vector 'a' and populate it with the numbers n through m
            a(a==                                   % Logically index into a, where the values of a match Disarium numbers
                cell2mat(                           % Convert the cell array returned by arrayfun into a matrix, so we can use it in the logical index
                    arrayfun(@(x){                  % Call the following function on every element of a, using the index named 'x'
                        sum(                        % Sum the matrix that results from the following computation
                            (f(x)-'0')              % Convert the value at index x into a string, then break it into a matrix by subtracting the string '0'.
                                                    % This results in the matrix [1 3 5] for the number 135.
                                .^                  % Compute the element-wise power with the following matrix
                                    (1:nnz(f(x)))   % Create a matrix with the range 1 to the length of the number at index x. This results in the matrix
                                                    % [1 2 3] for the number 135.
                        )                           % Closes the sum statement
                    },a)                            % Closes the arrayfun statement, passing the matrix a to be operated on
                )
            )

```

# Answer
> 1 votes
## Batch, 115 bytes

```
@for %%d in (0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427 2646798)do @if %%d geq %1 if %%d leq %2 echo %%d

```

Batch only has 32-bit arithmetic which has no way of comparing the last disarium number, but if you insist on string comparisons, then for 402 bytes:

```
@echo off
for %%d in (0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427 2646798 12157692622039623539)do call:c %1 %%d&&call:c %%d %2&&echo %%d
exit/b
:c
call:p %1 %2
set r=%s%
call:p %2 %1
:g
if %r:~,1% lss %s:~,1% exit/b0
if %r:~,1% gtr %s:~,1% exit/b1
if %r%==%s% exit/b0
set r=%r:~1%
set s=%s:~1%
goto g
:p
set s=%1
set t=%2
:l
set s=0%s%
set t=%t:~1%
if not "%t%"=="" goto l

```

# Answer
> 1 votes
## Scala, ~~132~~ 129 bytes

```
(% :Int,^ :Int)=>for(i<- %to^)if(((0/:(i+"").zipWithIndex)((z,f)=>{z+BigInt(f._1.toInt-48).pow(f._2+1).intValue}))==i)println(i)

```

---

129 edit: Changing the for loop's variable name from `&` to `i` saved three spaces.

---

## Explanation

For each value in the input range:

* convert it to a string with `+""`
* use `zipWithIndex` to produce a list of tuples containing a char of the digit and its index
* fold the list by returning each char's int value minus 48 (lines up to 0-9) to the power of its list index plus one (to start at ^1)
* if the result matches the input, print it

---

## Comments

Finally got around to learning how `fold` and `zipWithIndex` work. I'm unhappy with the `int` conversions, but I am pleased with the succinctness of `fold` and `zipWithIndex`.

# Answer
> 1 votes
# Husk, 11 bytes

```
fS=oṠδṁ^ŀd…

```

Try it online!

# Explanation

```
fS=oṠδṁ^ŀd…
          … inclusive range m to n
f           filter:
  =          is the number equal to
   o     d   the number converted to digits
     δ       zipped with
        ŀ    range 1..length
      ṁ^     raise each digit to those powers
      ṁ      and sum them

```

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

```
i;j;a(n,m){char*p;for(i=n;i<m;i++-n||puts(p))for(n=j=0;j++<asprintf(&p,"%d",i);)n+=pow(p[j-1]-48,j);}

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.unicode`, 72 bytes

```
[ [a,b] [ dup present [ [ digit> ] dip 1 + ^ ] map-index Σ = ] filter ]

```

Try it online!

## Explanation:

* `[a,b] [ ... ] filter` Create a range from the inputs (inclusive) and collect numbers for which the quotation returns `t` into a sequence.
* `dup ... =` Create a copy of the input and see if it's equal to the sum of the digits raised to their indices (the `...` part).
* `present` Convert a number to a string.
* `[ ... ] map-index` Apply a quotation to each element of a sequence and collect the results into a sequence of the same length. However, also place the index of the element on top of the stack.
* `[ digit> ] dip` Since the index is on top of the stack, the actual element of the sequence is underneath the index, so we use `dip` to apply a quotation to the object underneath the top of the data stack. `digit>` converts a code point to a digit.
* `1 + ^` Add one to the index (since it's zero-based) and raise the digit to this power.
* `Σ` Sum.

# Answer
> 1 votes
# Thunno 2 `c`, 7 bytes

```
Iædż*S=

```

Try it online!

#### Explanation

```
Iædż*S=  # Implicit input
I        # Inclusive range
 æ       # Filtered by:
  d      #  Split it into digits
   ż     #  Push [1..length]
    *    #  Exponentiation
     S   #  Sum this list
      =  #  Equals the number?
         # Implicit output

```

# Answer
> 1 votes
# Arturo, 47 bytes

```
$=>[select&..&'n[0n=∑map digits n'x->x^<=1+]]

```

Try it!

# Answer
> 1 votes
# PowerShell Core, 78 bytes

```
param($a,$b)$a..$b|?{$i=0
$s=0
"$_"|% t*y|%{$s+=,$_*++$i-join'*'|iex}
$s-eq$_}

```

Try it online!

Alternatively, also for 78 bytes: Try it online!

# Answer
> 0 votes
# Java

```
s->{long i=0,j=0,c,d;for(;j!=s;){String []f=Long.toString(i).split("");for(d=0,c=0;d<f.length;)c+=Math.pow(Long.valueOf(f[d]),++d);if(i==c)j++;}return i;}

```

## Explanation

```
s    - index
i    - iteration variable
j    - matches
c    - sum of each digit^its index
d    - index of digit in i

```

# Answer
> 0 votes
# Python 3: 131 Bytes

```
n=int(input())
m=int(input())
R=[x for x in range(n,m+1)]
O=[sum(map(int,str(x)))for x in R]
F=[(x**(O.index(x)))for x in O]
L=[x for x in F for w in R if x==w]
print(list(set(L)))

```

After creating this code, it's become apparent that there are a limited number of disariums, so it might be more feasible to check for these explicitly rather than using so much list comprehension which is tough on big inputs to this solution.

Try it online!

# Answer
> 0 votes
# SmileBASIC, 100 bytes

```
INPUT N,M
FOR I=N TO M
S=0FOR J=1TO LEN(STR$(I))S=S+POW(VAL(STR$(I)[J-1]),J)NEXT
IF S==I THEN?I
NEXT

```

---
Tags: code-golf, sequence
---


title: Recover the prime from the prime power

text:
# Question
Title: Recover the prime from the prime power
**Definition**: a *prime power* is a natural number that can be expressed in the form pn where p is a prime and n is a natural number.

**Task**: Given a prime power pn \> 1, return the prime p.

**Testcases**:

```
input output
9     3
16    2
343   7
2687  2687
59049 3

```

**Scoring**: This is . Shortest answer in bytes wins.

# Answer
# 05AB1E, 1 byte

```
f

```

Try it online!
> 13 votes

# Answer
# Shakespeare Programming Language, ~~209~~ 207 bytes

```
T.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen tothy!Page:You cat!Scene V:.Page:You be the sum ofyou a cat!Be the product ofthe quotient betweenI you you worse I?If soLet usScene V.Open heart

```

Try it online!

`(I/you)*you<I` is shorter than `I%you>0` in SPL.
> 13 votes

# Answer
# Java 8, ~~46~~ ~~39~~ 37 bytes

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

```

-7 bytes indirectly thanks to *@Tsathoggua*.
-2 bytes thanks to *JoKing*

Try it online.

**Explanation:**

```
n->{               // Method with integer as both parameter and return-type
  int r=1;         //  Start the result-integer `r` at 1
  for(;n%++r>0;);  //  Increase `r` by 1 before every iteration with `++r`
                   //  and loop until `n` is divisible by `r`
  return r;}       //  After the loop, return `r` as result

```
> 7 votes

# Answer
# Python 3, ~~36~~ 35 bytes

*-1 byte thanks to mathmandan*

```
f=lambda n,x=2:n%x and f(n,x+1)or x

```

Try it online!

Recursive function that finds the first factor larger than 1
> 5 votes

# Answer
# MATL, ~~4~~ 3 bytes

```
Yfu

```

Try it online!

### Explanation:

```
       % Implicit input:      [59049]
Yf     % Prime factorization: [3 3 3 3 3 3 3 3 3 3]
  u    % Unique elements:     [3]
       % Implicit output

```
> 4 votes

# Answer
# Octave, 16 bytes

```
@(x)factor(x)(1)

```

Try it online!

### Explanation:

```
@(x)              % Anonymous function taking x as input
    factor(x)     % Prime factorization
             (1)  % Get the first element

```

Or:

```
@(x)max(factor(x))  % the makeup of makeup artists

```
> 4 votes

# Answer
# Whitespace, ~~80~~ ~~61~~ 60 bytes

```
[S S T  T   N
_Push_-1][S S S N
_Push_0][T  N
T   T   _Read_STDIN_as_number][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][S S S N
_Push_0][T  T   T   _Retrieve][S N
T   _Swap][T    S T T   _Modulo][N
T   T   N
_If_0_Jump_to_Label_LOOP][S S T T   N
_Push_-1][T S S N
_Multiply][T    N
S T _Print_as_number]

```

-20 bytes thanks to *@JoKing*.

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

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

**Explanation in pseudo-code:**

```
Integer n = STDIN as integer
Integer i = -1
Start LOOP:
  i = i - 1
  if(n modulo-i is negative)
    Go to next iteration of LOOP
  else
    i = i * -1
    Print i
    Exit with error: No exit defined

```

**Example run: `input = 9`**

```
Command   Explanation                    Stack        Heap     STDIN    STDOUT    STDERR

SSTTN     Push -1                        [-1]
SSSN      Push 0                         [-1,0]
TNTT      Read STDIN as integer          [-1]         {0:9}    9
NSSN      Create Label_LOOP              [-1]         {0:9}
 SSSTN    Push 1                         [-1,1]       {0:9}
 TSST     Subtract top two (-1-1)        [-2]         {0:9}
 SNS      Duplicate top (-2)             [-2,-2]      {0:9}
 SSSN     Push 0                         [-2,-2,0]    {0:9}
 TTT      Retrieve                       [-2,-2,9]    {0:9}
 SNT      Swap top two                   [-2,9,-2]    {0:9}
 TSTT     Modulo top two (9%-2)          [-2,-1]      {0:9}
 NTSN     If neg.: Jump to Label_LOOP    [-2]         {0:9}

 SSTTN    Push -1                        [-2,-1]      {0:9}
 TSST     Subtract top two (-2-1)        [-3]         {0:9}
 SNS      Duplicate top (-2)             [-3,-3]      {0:9}
 SSSN     Push 0                         [-3,-3,0]    {0:9}
 TTT      Retrieve                       [-3,-3,9]    {0:9}
 SNT      Swap top two                   [-3,9,-3]    {0:9}
 TSTT     Modulo top two (9%-3)          [-3,0]       {0:9}
 NTSN     If neg.: Jump to Label_LOOP    [-3]         {0:9}
 SSTTN    Push -1                        [-3,-1]      {0:9}
 TSSN     Multiply top two (-3*-1)       [3]          {0:9}
 TNST     Print as integer               []           {0:9}             3
                                                                                error

```

Program stops with an error: No exit found.
> 4 votes

# Answer
# JavaScript (ES6), 25 bytes

```
f=(n,k=2)=>n%k?f(n,k+1):k

```

Try it online!
> 3 votes

# Answer
# Funky, 30 bytes

```
n=>fori=2n>i i++if1>n%i breaki

```

Try it online!
> 3 votes

# Answer
# Pyth, 2 bytes

```
hP

```

Try it here!
> 2 votes

# Answer
# Jelly, 3 bytes

```
ÆfḢ

```

Try it online!

`ÆfṪ`, `ÆfX` could also be seriously competing functions.
`ÆfQ` could be a seriously competing full program.
> 2 votes

# Answer
# C (gcc), 28 bytes

```
f(k,p){for(p=1;k%++p;);k=p;}

```

Try it online!
> 2 votes

# Answer
# Forth (gforth), 34 bytes

```
: f 1 begin 1+ 2dup mod 0= until ;

```

Try it online!

### Explanation

1. Iterate integers starting from 2
2. Stop and return when you find one that divides n with no remainder

### Code Explanation

```
: f               \ Define a new word
  1               \ place a 1 on the stack (to use as a counter/index)
  begin           \ start indefinite loop
    1+ 2dup       \ increment counter and duplicate counter and prime power
    mod           \ calculate power % index
  0= until        \ end the loop if modulus is 0 (no remainder)
;                 \ end word definition

```
> 2 votes

# Answer
# , ~~32~~ 26 bytes

@Giuseppe with different logic and a shorter solution:

```
(x=2:(n=scan()))[!n%%x][1]

```

Try it online!

Original:

```
numbers::primeFactors(scan())[1]

```

Try it online!

This is obviously a much superior port of the 05AB1E solution.
> 2 votes

# Answer
# APL (Dyalog Extended), ~~7~~ 2 bytes

```
⊃⍭

```

Try it online!

gives a list of factors,  gets the first of them.
> 2 votes

# Answer
# Vyxal 1, 1 byte

There was a builtin just for this.
> 2 votes

# Answer
# Regex (ECMAScript), 10 bytes

```
(xx+?)\1*$

```

Try it online!

Works by finding the smallest prime factor. Takes its input in bijective unary, as a sequence of `x` characters in which the length represents the number. The output is returned in capture group 1.

```
         # No anchor needed, since every input N>=2 returns an output
(xx+?)   # \1 = the smallest number >=2 for which:
\1*$     # N-\1 is divisible by \1

```
> 2 votes

# Answer
# Brachylog, 2 bytes

```
ḋh

```

Try it online!

### Explanation

```
ḋ       Prime decomposition
 h      Head

```
> 1 votes

# Answer
# , 4 bytes

```
0{q:

```

Select `{` the first `0` of the prime factors `q:`

Try it online!
> 1 votes

# Answer
# Neim, 1 byte

```

```

Try it online!
> 1 votes

# Answer
# Haskell, 26 bytes

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

```

Try it online!
> 1 votes

# Answer
# Mathematica, 17 bytes

```
Divisors[#][[2]]&

```

The second smallest divisor.
> 1 votes

# Answer
# Husk, 2 bytes

```
←p

```

Try it online!
> 1 votes

# Answer
# ARBLE, 19 bytes

```
index(factors(a),1)

```

Try it online!
> 0 votes

# Answer
# Japt `-g`, 1 byte

```
k

```

Try it here
> 0 votes

# Answer
# Python 3, ~~47~~ ~~45~~ 44 bytes

*Inspired by Kevin Cruijssen's answer in Java*.

*~~2~~ 3 bytes removed thanks to Jo King*.

```
lambda n:[i+1for i in range(n)if n%-~i<1][1]

```

Try it online!
> 0 votes

# Answer
# PowerShell, 31 bytes

```
param($a)(2..$a|?{!($a%$_)})[0]

```

Try it online!

Constructs a range from `2` to input `$a`, pulls out those elements `where` (`?`) the modulo operation `%` results in a zero `!(...)` (i.e., those that are divisors of `$a`), and then takes the smallest `[0]` one thereof. That's left on the pipeline, output is implicit.
> 0 votes

# Answer
# Visual Basic .NET (.NET Framework v4.5), ~~123~~ 71 bytes

*-52 bytes thanks to @Jo King*

```
Function A(n)
For i=n To 2 Step-1
A=If(n Mod i=0,i,A)
Next
End Function

```

Try it online!

Ungolfed:

```
Function A(input As Long) As Long
    For i = input To 2 Step -1
        A = If (input Mod i = 0, i, A)
    Next
End Function

```

Explanation:

The `i` loop searches backwards from the first number, and finds all numbers that divide it evenly. Because we are going backwards, the smallest is stored in the vairable `A`.

VB gives you a free variable that matches your function name (in my case, `A`). At the end of the function execution, the value in that variable is returned (barring an explicit `Return` statement.
> 0 votes

# Answer
# Perl 6, 22 bytes

```
{grep($_%%*,2..$_)[0]}

```

Try it online!

Anonymous code block that filters the factors of the range of 2 to the input and returns the first one. I tried using `^$` to save 2 bytes, but that didn't work in the case that the input was prime.
> 0 votes

# Answer
# Haskell, 29 bytes

```
f y=[x|x<-[2..],mod y x<1]!!0

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 17 bytes

```
n->factor(n)[1,1]

```

Try it online!

---

# Pari/GP, 17 bytes

```
n->divisors(n)[2]

```

Try it online!
> 0 votes

# Answer
# Ruby, 100 bytes

```
require"prime"
i=gets.to_i
Prime.each(i){|p|(1..i).each{|n|c=p**n==i
    puts p if c
    exit if c}}

```

Try it online!
> 0 votes

# Answer
# Stax, 3 bytes

```
|fh

```

Run and debug it

First element of prime factorization.
> 0 votes

# Answer
# Julia 0.6, 25 bytes

```
n->[2:n;][n.%(2:n).<1][1]

```

Try it online!
> 0 votes

# Answer
# Ruby, 26 bytes

```
->n,i=1{(1>n%i+=1)?i:redo}

```

Try it online!
> 0 votes

# Answer
# QBasic, 39 bytes

```
INPUT x
p=2
WHILE x\p<x/p
p=p+1
WEND
?p

```

Trial division; finds the first factor greater than 1, which is guaranteed to be the prime factor.

The only trick here is the condition `x\p<x/p`, which uses integer vs. floating point division to test whether "`x` is not divisible by `p`." See this tip for details.
> 0 votes

# Answer
# Thunno 2, 1 byte

```
Ƒ

```

Try it online!

Unique prime factors built-in.
> 0 votes

# Answer
# Desmos, 32 bytes

*-17 bytes thanks to @Aiden Chow!*

```
d=[2...n]
f(n)=d[mod(n,d)=0].min

```

Try it on Desmos!

Find the smallest factor (\>1) of \\$n\\$.

# Desmos, 49 bytes

```
p=[\sqrt[i]n\for i=[n...1]]
f(n)=p[\ceil(p)=p][1]

```

**Explaination**

Finds the smallest integer value of \\$\sqrt\[i\]n\\$ (\\$i\in\mathbb Z\\$)

In other words, make \\$\sqrt\[i\]n\\$ an integer with the greatest value of \\$i\\$

Try it on Desmos!
> 0 votes

# Answer
# ARBLE, 17 bytes

```
primefactors(n)/z

```

Try it online!
> 0 votes

---
Tags: code-golf, arithmetic, primes
---


title: Shift Braille down

text:
# Question
Title: Shift Braille down
Braille Patterns in Unicode contains 8 dots() and occupy area U+2800-U+28FF. Given a Braille Pattern character, where the bottom two dots are not used(aka. U+2800-U+283F), shift it down by one dot.

Test cases:

```
⠀ => ⠀ (U+2800 -> U+2800)
⠅ => ⡂
⠕ => ⡢
⠿ => ⣶

```

Shortest code wins.

# Answer
> 12 votes
# Python, 44 bytes

```
lambda c:chr((d:=ord(c))+d%64+14*(d&36)%192)

```

Attempt This Online!

Takes and returns a Unicode character.

# Python, 29 bytes

```
lambda c:c+c%64+14*(c&36)%192

```

Attempt This Online!

Takes and returns a code point.

### Python, 33 bytes

```
lambda c:c+c%64+2*(c&32)+14*(c&4)

```

Attempt This Online!

Takes and returns a code point.

# Answer
> 11 votes
# Jelly, 7 bytes

```
B⁽1¢œ?Ḅ

```

Try It Online!

I/O via unicode codepoints.

## Explanation

```
B⁽1¢œ?Ḅ    Main Link
B          Convert to binary
 ⁽1¢œ?     Take the 13252nd permutation, which shuffles the last 8 bits into place
      Ḅ    Convert from binary

```

My original idea was to chop off the first 7 bits to apply permutation and then add 10240, but Lynn made the clever observation that permutation number 13252 only modifies the last 8 bits so it's not needed to do those precomputation and postcomputation steps.

-5 bytes thanks to emanresu A and Jonathan Allan by using a more convenient input format.
-6 bytes thanks to Lynn by noticing that removing and re-adding the first 7 bits is not needed

# Answer
> 3 votes
# JavaScript (ES6), 25 bytes

Expects and returns a code point.

```
n=>n+n%64+((n/4&9)+3^3)*8

```

Try it online!

### 23 bytes

A port of loopy walt's solution is shorter.

```
n=>n+n%64+14*(n&36)%192

```

Try it online!

# Answer
> 3 votes
# Retina, ~~178~~ ~~163~~ 150 bytes

```
.
255*x
Y`x`⠁-⣿

~)`.+
Y`$0`$-1
~(K`T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶

-

```

Try it online!

*-15 with another eval stage*

*-6 directly thanks to Neil and -7 extrapolating from his suggestions*

Shaves a few bytes off direct transliteration by spending 40 on an incredibly convoluted way of "doubling" the input so the final transliteration stage can use more ranges. The doubling is necessary because every possible output is even; if the bits in a byte are `76543210` then the dots in the corresponding Braille character are

```
0 3
1 4
2 5
6 7

```

(Although this handles longer inputs fine, in the explanation I'll assume only the single character input required by the challenge for the sake of simplicity.)

# Explanation:

The entire program consists of two eval stages, which construct then run Retina programs:

## Eval stage 1

```
.
255*x

```

Replace any and all characters in the input with 255 copies of the letter `x`.

```
Y`x`⠁-⣿

```

Cycling transliterate those into the range of all 255 nonzero Braille characters. This creates that range as a string.

```

```

Replace the empty string with a space, prepending a space to every character in the range and appending another to the end.

```
.+
Y`$0`$-1

```

Interpolate the spaced range and the unspaced range into the string representation of a cyclic transliterate.

## Eval stage 2

```
K`T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶

```

The literal string `T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶`.

```

-

```

Replace the empty string with a hyphen, prepending a hyphen to every character in the string and appending another to the end.

## What actually gets run on the input

```
Y` ⠁ ⠂ ⠃ ⠄ ⠅ ⠆ ⠇ ⠈ ⠉ ⠊ ⠋ ⠌ ⠍ ⠎ ⠏ ⠐ ⠑ ⠒ ⠓ ⠔ ⠕ ⠖ ⠗ ⠘ ⠙ ⠚ ⠛ ⠜ ⠝ ⠞ ⠟ ⠠ ⠡ ⠢ ⠣ ⠤ ⠥ ⠦ ⠧ ⠨ ⠩ ⠪ ⠫ ⠬ ⠭ ⠮ ⠯ ⠰ ⠱ ⠲ ⠳ ⠴ ⠵ ⠶ ⠷ ⠸ ⠹ ⠺ ⠻ ⠼ ⠽ ⠾ ⠿ ⡀ ⡁ ⡂ ⡃ ⡄ ⡅ ⡆ ⡇ ⡈ ⡉ ⡊ ⡋ ⡌ ⡍ ⡎ ⡏ ⡐ ⡑ ⡒ ⡓ ⡔ ⡕ ⡖ ⡗ ⡘ ⡙ ⡚ ⡛ ⡜ ⡝ ⡞ ⡟ ⡠ ⡡ ⡢ ⡣ ⡤ ⡥ ⡦ ⡧ ⡨ ⡩ ⡪ ⡫ ⡬ ⡭ ⡮ ⡯ ⡰ ⡱ ⡲ ⡳ ⡴ ⡵ ⡶ ⡷ ⡸ ⡹ ⡺ ⡻ ⡼ ⡽ ⡾ ⡿ ⢀ ⢁ ⢂ ⢃ ⢄ ⢅ ⢆ ⢇ ⢈ ⢉ ⢊ ⢋ ⢌ ⢍ ⢎ ⢏ ⢐ ⢑ ⢒ ⢓ ⢔ ⢕ ⢖ ⢗ ⢘ ⢙ ⢚ ⢛ ⢜ ⢝ ⢞ ⢟ ⢠ ⢡ ⢢ ⢣ ⢤ ⢥ ⢦ ⢧ ⢨ ⢩ ⢪ ⢫ ⢬ ⢭ ⢮ ⢯ ⢰ ⢱ ⢲ ⢳ ⢴ ⢵ ⢶ ⢷ ⢸ ⢹ ⢺ ⢻ ⢼ ⢽ ⢾ ⢿ ⣀ ⣁ ⣂ ⣃ ⣄ ⣅ ⣆ ⣇ ⣈ ⣉ ⣊ ⣋ ⣌ ⣍ ⣎ ⣏ ⣐ ⣑ ⣒ ⣓ ⣔ ⣕ ⣖ ⣗ ⣘ ⣙ ⣚ ⣛ ⣜ ⣝ ⣞ ⣟ ⣠ ⣡ ⣢ ⣣ ⣤ ⣥ ⣦ ⣧ ⣨ ⣩ ⣪ ⣫ ⣬ ⣭ ⣮ ⣯ ⣰ ⣱ ⣲ ⣳ ⣴ ⣵ ⣶ ⣷ ⣸ ⣹ ⣺ ⣻ ⣼ ⣽ ⣾ ⣿`⠁⠂⠃⠄⠅⠆⠇⠈⠉⠊⠋⠌⠍⠎⠏⠐⠑⠒⠓⠔⠕⠖⠗⠘⠙⠚⠛⠜⠝⠞⠟⠠⠡⠢⠣⠤⠥⠦⠧⠨⠩⠪⠫⠬⠭⠮⠯⠰⠱⠲⠳⠴⠵⠶⠷⠸⠹⠺⠻⠼⠽⠾⠿⡀⡁⡂⡃⡄⡅⡆⡇⡈⡉⡊⡋⡌⡍⡎⡏⡐⡑⡒⡓⡔⡕⡖⡗⡘⡙⡚⡛⡜⡝⡞⡟⡠⡡⡢⡣⡤⡥⡦⡧⡨⡩⡪⡫⡬⡭⡮⡯⡰⡱⡲⡳⡴⡵⡶⡷⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⢈⢉⢊⢋⢌⢍⢎⢏⢐⢑⢒⢓⢔⢕⢖⢗⢘⢙⢚⢛⢜⢝⢞⢟⢠⢡⢢⢣⢤⢥⢦⢧⢨⢩⢪⢫⢬⢭⢮⢯⢰⢱⢲⢳⢴⢵⢶⢷⢸⢹⢺⢻⢼⢽⢾⢿⣀⣁⣂⣃⣄⣅⣆⣇⣈⣉⣊⣋⣌⣍⣎⣏⣐⣑⣒⣓⣔⣕⣖⣗⣘⣙⣚⣛⣜⣝⣞⣟⣠⣡⣢⣣⣤⣥⣦⣧⣨⣩⣪⣫⣬⣭⣮⣯⣰⣱⣲⣳⣴⣵⣶⣷⣸⣹⣺⣻⣼⣽⣾⣿

```

The program generated and run in eval stage 1. Transliterates the input to the character at twice its index in the Braille range, "doubling" it.

```
-T-`-⠂-⣿-`-⠂-⠆-⡀-⡆-⠐-⠖-⡐-⡖-⠠-⠦-⡠-⡦-⠰-⠶-⡰-⡶-⢀-⢆-⣀-⣆-⢐-⢖-⣐-⣖-⢠-⢦-⣠-⣦-⢰-⢶-⣰-⣶-

```

The program generated and run in eval stage 2. Transliterates the doubled input into a bunch of smaller ranges.

The ranges are non-overlapping pairs of non-hyphens in the `to` section after the rightmost backtick; the hyphens not inside those pairs parse as literal hyphens which are used for alignment (as the whole point of this is that the `from` range, between the backticks, is not doubled.) The final hyphen in both the `from` and `to` sections is completely irrelevant and the leading hyphens cancel each other out; the extra hyphens before the first backtick are just ignored.

# Answer
> 2 votes
# Python, ~~77~~ 64 bytes

*-2 bytes thanks to l4m2*

```
lambda c:[c&32and(c:=c&~32|64),c&4and(c:=c&~4|32),c*2-0x2800][2]

```

Attempt This Online!

Input/output in Unicode codepoints.

## Ungolfed

```
def f(c):
    # fix exceptions (Historical Reasons™)
    if c & 32: # change bit 7 set to bit 8 set
        c &= ~32
        c |= 64
    if c & 4: # change bit 4 set to bit 7 set
        c &= ~4
        c |= 32
    return (c << 1) - 0x2800

```

See https://en.wikipedia.org/wiki/Braille\_Patterns#Identifying,\_naming\_and\_ordering for more info.

# Answer
> 2 votes
# Go, 45 bytes

```
func(c rune)rune{return c+c%64+14*(c&36)%192}

```

Try it online!

Port of loopy walt's Python answer.

# Answer
> 2 votes
# , 12 bytes

```
13251#.@A.#:

```

Attempt This Online!

Apparently converged at the same algorithm as Jelly, because both have the "nth permutation" built-in. (This is not magically winning against Jelly; the direct translation is Lynn's 7-byter in the comments.)

Looking at the lower 8 bits of a Braille's codepoint (highest bit first), the main task is to permute the first into the second:

```
 0  0 b2 b3 b4 b5 b6 b7
b2 b5 b3 b4  0 b6 b7  0

```

It doesn't matter which of the two guaranteed zeros go first, so 13257 also works in place of 13251. Jelly uses 13252 instead because its built-in is 1-indexed instead of 0-indexed.

# Answer
> 1 votes
# Charcoal, 23 bytes

```
℅Σ⟦℅θ＆℅θ⁶³×¹⁴＆℅θ⁴⊗＆℅θ³²

```

Try it online! Link is to verbose version of code. Explanation: Port of @loopywalt's original Python answer.

```
    θ                   Input character
   ℅                    Code of character
       θ                Input character
      ℅                 Code of character
     ＆                  Bitwise And
        ⁶³              Literal integer `63`
               θ        Input character
              ℅         Code of character
             ＆          Bitwise And
                ⁴       Literal integer `4`
          ×             Multiplied by
           ¹⁴           Literal integer `14`
                    θ   Input character
                   ℅    Code of character
                  ＆     Bitwise And
                     ³² Literal integer `32`
                  ⊗     Doubled
  ⟦                     Make into list
 Σ                      Take the sum
℅                       Character with code
                        Implicitly print

```

Alternative version, also 23 bytes:

```
≔℅Ｓθ℅Σ⟦θ＆θ⁶³×¹⁴＆θ⁴⊗＆θ³²

```

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

24 bytes for a whole string at once:

```
⭆ＥＳ℅ι℅Σ⟦ι＆ι⁶³×¹⁴＆ι⁴⊗＆ι³²

```

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

# Answer
> 1 votes
# Retina 0.8.2, 199 bytes

```
T`⠁-⠿`⠂⠄⠆⡀⡂⡄⡆⠐⠒⠔⠖⡐⡒⡔⡖⠠⠢⠤⠦⡠⡢⡤⡦⠰⠲⠴⠶⡰⡲⡴⡶⢀⢂⢄⢆⣀⣂⣄⣆⢐⢒⢔⢖⣐⣒⣔⣖⢠⢢⢤⢦⣠⣢⣤⣦⢰⢲⢴⢶⣰⣲⣴⣶

```

Try it online! Link includes test cases. Explanation: Unfortunately there doesn't seem to be a good way to encode the destination characters as their codes jump all over the place. I looked into shifting the codes into the ASCII range to do the transliteration but that looks as if it will take 239 bytes.

# Answer
> 1 votes
# Scala 3, 48 bytes

Port of @loopy walt's Python answer in Scala.

---

```
c=>{val d=c.toInt;(d+d%64+14*(d&36)%192).toChar}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
bœŽp÷èC

```

Port of *@hyper-neutrino♦*'s Jelly answer, so make sure to upvote that answer as well!

I/O as codepoint integers.

No TIO, since it's way too slow (it'll get a list of all binary-permutations and indexes into it).

**Much faster version which does finish - 11 (or 9) bytes:**

<sup>*†: Should have been 9 bytes without the `ƶ` and `Ā`, but apparently there is a bug with the \\$n^{th}\\$ permutation builtin `.I` and bit-lists..*</sup>

```
2вƶŽp÷.IĀ2β

```

I/O as codepoint integers.

Try it online or verify all test cases.

**Explanation:**

```
b            # Convert the (implicit) input-integer to a binary-string
 œ           # Get all permutations of this binary-string
  Žp÷        # Push compressed integer 13251
     è       # Index it into the list of permutations
      C      # Convert this permuted binary-string back to a (base-10) integer
             # (which is output implicitly as result)

```

```
2в           # Convert the (implicit) input-integer to a binary-list
  ƶ          # Multiply each 1 to its 1-based index (bug workaround part 1 of 2)
   Žp÷       # Push compressed integer 13251
      .I     # Get the 0-based 13251st permutation of the list
        Ā    # Convert each positive integer back to 1s (bug workaround part 2 of 2)
         2β  # Convert this permuted binary-list back to a (base-10) integer
             # (which is output implicitly as result)

```

Note: `.I` only works with lists and not with strings.

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Žp÷` is `13251`.

# Answer
> 1 votes
# Java, 23 bytes

```
c->c+c%64+(c&36)*14%192

```

Another port of *@loopyWalt*'s Python answer.
I/O as codepoint-integers.

Try it online.

With characters as I/O, it would be 1 byte longer:

```
c->c+=c%64+(c&36)*14%192

```

Try it online.

**Explanation (of the character I/O lambda function):**

```
c->                 // Method with character as both parameter and return-type
  c+=               //  Add to the current codepoint-integer, without changing its type:
     c%64           //   The input-codepoint modulo-64
     +              //   As well as:
      (c&36)        //    The input-codepoint basewise-AND with 36
            *14     //    Then multiplied by 14
               %192 //    And then modulo-192

```

---
Tags: code-golf, unicode
---