title: Code a code page

text:
# Question
Title: Code a code page
# Introduction

A code page maps integer values to a specific character. We can visualize a code page like this:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

```

The rows specify the first digit and the columns the second digit of the hex-number.

# The Challenge

Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value. The input `qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ` for example would yield the table above.

* The output has to be in the exact same format as the table above. Only a trailing newline is optional.
* If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).
* Each character is placed exactly in the middle of a cell, padded by one space to the left and right.
* The values in the first row and column are given by hex-numbers with the digits `0123456789ABCDEF`. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.
* The only characters present in the output are hyphens `-`, pluses `+`, pipes `|`, spaces , the digits for hexadecimal numbers and the characters from the input.
* Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.
* You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.
* If your language can **only** handle ASCII input, you may assume ASCII-only input and repeated characters.

# Rules

**Happy Coding!**

# Answer
## Pyth, 60 bytes

```

K+*"+---"hJ16\+Vm++"| "j" | "d" |"+]+]d.HMJ.e+.Hk.[bdJczJNK

```

The leading newline is significant.

Try it here.
> 7 votes

# Answer
# Python 3.5, 326 355 bytes:

(*+29 bytes since if the length of the last row is **not** a multiple of 16, unused cells should be left empty (although, in my opinion, it looks much better if those empty cells are just not even shown)*)

```
def f(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]),end='');print('  |'+'   |'*(15-len(r[-1]))+'\n'+'+---'*17+'+')

```

Works like a charm!

**Sample Inputs and Outputs:**

```
Input: 'hopper'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | o | p | p | e | r |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Input: 'honkhonkhonkhonkhonk'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | o | n | k | h | o | n | k | h | o | n | k | h | o | n | k |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 1 | h | o | n | k |   |   |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

Input: 'hi'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | h | i |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

```

I hope this is okay.

Also, here is another version I created for this challenge, which, although is an invalid candidate since it does **not** print out extra empty cells for the last row if its length is not a multiple 16, in my opinion outputs a much better looking page than the one required by OP, mainly because it does not even show empty cells if the last row is not a multiple of 16, but instead just shows filled cells, and that's it:

```
def f2(r):o=' 0123456789ABCDEF';r=[r[0+i:16+i]for i in range(0,len(r),16)];print('+---'*17+'+\n|',end='');[print(' {} |'.format(h),end='')for h in o];print(''.join([str(e+' | ')if e.isdigit()or e.isalpha()else str(e)for e in''.join([str('\n'+'+---'*17+'+\n| '+x[0]+x[1])for x in zip(o[1::1],r)])]));print('+---'*(len(r[-1])+1)+'+')

```

Here is a sample input and output for the inapplicable code above:

```
Input: 'ggreuuobgugoubgoubguorgoruguor'

Output:

    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    |   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 0 | g | g | r | e | u | u | o | b | g | u | g | o | u | b | g | o |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    | 1 | u | b | g | u | o | r | g | o | r | u | g | u | o | r |
    +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    (As you can see, there are no empty cells shown in the entire table. This looks much better to me.)

```
> 7 votes

# Answer
# Excel VBA, <sub>~~157~~</sub> 146 Bytes (Cheating?)

Anonymous VBE Immediate Window function that destructively takes input from range `[A1]` and outputs to the `ActiveSheet` object.

### Golfed

```
[B1:Q1]="=Dec2Hex(Column(B1)-2)":L=[Len(A1)]:For i=0To l:Cells(i\16+2,i Mod 16+2)=Mid([A1],i+1,1):Next:For i=1To l\16+1:Cells(i+1,1)=i:Next:[A1]="

```

### Formatted

```
[B1:Q1]="=Dec2Hex(Column(B1)-2)"
L=[Len(A1)]
For i=0To l:Cells(Int(i/16)+2,i Mod 16+2)=Mid([A1],i+1,1):Next
For i=1To Int(l/16)+1:Cells(i+1,1)=i:Next
[A1]=""

```

### Input / Output

Given:

```
[A1]="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJ"

```

the generated output is
> 4 votes

# Answer
# Excel (Version 1911), 247

```
A1 =DEC2HEX(COLUMN(A1:P1)-1)
A2 'Input String
A3 =2+LEN(A2)/16
A4 =CONCAT(" ",C2#)
A5 =TEXTJOIN("
"&REPT("+---",17)&"+
",0,,"| "&MID(A4,B2#+1,1)&" | "&MID(TEXTJOIN(" | ",0,A1#,MID(A2&REPT(" ",16),HEX2DEC(C2#&A1#)+1,1)),B2#*64+1,61)&" |",) ' Output
B2 =SEQUENCE(A3)-1
C2 =DEC2HEX(SEQUENCE(A3-1)-1)

```

Sample Test

# Excel (Joke answer), 88 Bytes

Not a valid solution, but fun

```
B2 'Input
C4 =DEC2HEX(SEQUENCE(,16,0))
B5 =DEC2HEX(SEQUENCE(1+LEN(B2)/16)-1)
C5 =MID(B2,HEX2DEC(B5#&C4#)+1,1)

```

Output
> 4 votes

# Answer
## JavaScript (ES6), 148 bytes

```
s=>(s=' 0123456789ABCDEF'+s+' '.repeat(15)).match(/(?!^).{16}/g).map((t,i)=>d+`+
| `+[s[i],...t].join` | `,d=`+---`.repeat(17)).join` |
`+` |
${d}+`

```

The `' 0123456789ABCDEF'` exists to populate the first column, but conveniently also covers the first row. The input string is then padded with spaces to allow it to be split into substrings of length 16, with the `(?!^)` preventing the leading space from being matched. The rest is just joining up the pieces.
> 3 votes

# Answer
# 05AB1E, ~~65~~ 63 bytes

Code:

```
"+---"17×'+J©,žhAu6£¹J16÷)v„| ?N>iðëN<16B}y«ð17×ðñvy„ |ðJ?}¶?®,

```

Try it online!. Uses **CP-1252** encoding.
> 3 votes

# Answer
# PowerShell, ~~127~~ ~~126~~ 121 bytes

```
($d='+---'*17+'+')
($n="0123456789ABCDEF$args"+' '*16)|sls '.{16}'-a|% m*|% v*|%{"$($n[$i++-1]+$_|% t*y|%{"| $_"}) |"
$d}

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-pF`, ~~134~~ ~~109~~ 106 bytes

```
@F=(@a=($",0..9,A..F),@F);shift@F;printf+($_="+---"x@a.'+
')."|%2s "x@a."|
",$a[$i++],splice@F,0,16while@F

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-pl`, ~~127~~ 120 bytes

```
@.=($",0..9,A..F);$\='+---'x@..'+
';$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$\$&|
;g

```

Try it online!

Previous version:

```
@.=($",0..9,A..F);$~='+'.'---+'x@.;$_=join'',@.,s;.{1,16};$.[$.++].sprintf'%-16s',$&;gre;s;.;| $& ;g;s;.{1,68};$~
$&|
;g;$_.=$~

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~47~~ 45 bytes

Thanks to Kevin Cruijssen for -2 bytes!

```
16ôí16jí15ÝhJš¬ðìsøv"+---"69∍=yS3j€ÀõšĆ'|ý,},

```

Try it online!

**Commented**:

```
16ô                     # split the input into groups of (up to) 16
   í16jí                # right-pad the groups to 16 with reverse, left-pad, reverse
        15Ý             # push [0, 1, ..., 15]
           hJ           # convert each number to hexadecimal and join into string
                        #  => "0123456789ABCDEF"
               š        # prepend this string to the list
                ¬       # get the string back from the list
                 ðìs    # prepend a space
                    ø   # zip the list and the string

v              }        # iterate over the list
 "+---"                 # push the string "+---"
       69∍              # extend it to length 69
          =             # print it without removing the string from the stack
 y                      # push the current entry
  S                     # split into a list of characters
   3j                   # left-pad each to 3 chars with spaces
     €À                 # rotate each string left
       õšĆ              # prepend and append the empty string
          '|ý           # join by "|"
             ,          # print the string

,                       # after the loop: print "+---"69∍, which is still on the stack

```

Try the first part with step-by-step output
Try one loop-iteration with step-by-step output
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Surrounded Countries

text:
# Question
Title: Surrounded Countries
Countries own a series of territories on a 1D world. Each country is uniquely identified by a number. Ownership of the territories can be represented by a list as follows:

```
1 1 2 2 1 3 3 2 4

```

We define a country's edgemost territories as the two territories closest to either edge. If the above list was zero indexed, country `1`'s edgemost territories occur at position `0` and `4`.

A country *surrounds* another if the sublist between its two edgemost territories contains all the territories of another country. In the above example, the sublist between country `2`'s edgemost territories is:

```
2 2 1 3 3 2

```

And we see that all the territories of country `3` are between the edgemost territories of country `2`, so country `2` surrounds country `3`.

A country with only one element will never surround another.

## Challenge

Take a list of integers as input (in any format) and output a *truthy* value if any country is surrounded by another, and a *falsy* value otherwise.

You can assume that the input list is nonempty, only contains positive integers, and does not 'skip' any numbers: for example, `1 2 1 5` would be invalid input.

## Test Cases

```
+----------------------+--------+
|        Input         | Output |
+----------------------+--------+
| 1                    | False  |
| 2 1 3 2              | True   |
| 2 1 2 1 2            | True   |
| 1 2 3 1 2 3          | False  |
| 1 3 1 2 2 3 2 3      | True   |
| 1 2 2 1 3 2 3 3 4    | False  |
| 1 2 3 4 5 6 7 8 9 10 | False  |
+----------------------+--------+

```

# Answer
## Pyth, 7 bytes

```
n{Q_{_Q

```

Run the code on test cases.

```
n      Check whether the following are not equal:
 {Q     The unique elements in order of first appearance
 _{_Q   The unique elements in order of last appearance
         (done by reversing, taking unique elts, then reversing again)

```

The only way to avoid surrounding is for the countries' leftmost territories to be sorted in the same order as their rightmost territories. If two countries are swapped in this order, one has a territory both further left and further right than the other, and so surrounds it.

To obtain the unique countries in order of leftmost territory, we simply deduplicate, which preserves this order. The same is done for the rightmost territory by reversing, deduplicating, then reversing again. If these give different results, then a country is surrounded.
> 35 votes

# Answer
## Retina, ~~61~~ 60 bytes

Much longer than I would like...

```
(\b(\d+)\b.* (?!\2 )(\d+) .*\b\2\b)(?!.* \3\b)(?<!\b\3 .*\1)

```

Prints the number of countries that surround at least one other country.

Try it online.

It's a very straightforward implementation of the spec: we look for the pattern `A...B...A` such that `B` appears neither before or after the match.
> 12 votes

# Answer
## Python, 64 bytes

```
lambda l,S=sorted:S(l,key=l.index)!=S(l,key=l[::-1].index)[::-1]

```

The only way to avoid surrounding is for the countries' leftmost territories to be sorted in the same order as their rightmost territories. If two countries are swapped in this order, one has a territory both further left and further right than the other, and so surrounds it.

The function checks that sorting the territories by leftmost appearance and rightmost appearance gives the same results. Unfortunately, Python lists don't have `rindex` analogous to `rfind`, so we reverse the list, then reverse the sorted output.

Same length (64) with an auxiliary function:

```
g=lambda l:sorted(l,key=l.index)
lambda l:g(l)[::-1]!=g(l[::-1])

```
> 11 votes

# Answer
# C#, 113 bytes

```
public bool V(int[] n){var u1=n.Distinct();var u2=n.Reverse().Distinct().Reverse();return !u1.SequenceEqual(u2);}

```

Ungolfed:

```
public bool ContainsSurroundedCountry(int[] numbers)
{
    int[] uniqueLeftmost = numbers.Distinct().ToArray();
    int[] uniqueRightmost = numbers.Reverse().Distinct().Reverse().ToArray();

    return !uniqueLeftmost.SequenceEqual(uniqueRightmost);
}

```

Using a concise `LINQ` approach.
> 6 votes

# Answer
## CJam (14 13 bytes)

```
{__&\W%_&W%#}

```

Online demo

Thanks to Martin Büttner for a one-char saving.
> 5 votes

# Answer
## ES6, ~~76~~ ~~75~~ ~~65~~ 64 bytes

```
 a=>(f=r=>a.filter((x,i)=>a.indexOf(x,r&&i+1)==(r|i))+a)()!=f(-1)

```

Straightforward port of @xnor's answers.

Edit: Saved 1 byte by replacing `a.lastIndexOf(x)==i` with `a.indexOf(x,i+1)<0`.

Edit: Saved 10 bytes thanks to @user81655.

Edit: Saved 1 byte by replacing `r||i` with `r|i`.
> 4 votes

# Answer
# Japt, 12 bytes

```
Uâ ¬¦Uw â ¬w

```

Try it online!

Thanks to @xnor for figuring out the algorithm. Input array is automatically stored in `U`, `â` is uniqify, `w` is reverse, and `¦` is `!=`. `¬` joins with the empty string (`[1,2,3] => "123"`); this is necessary because JavaScript's comparsion counts two arrays as not equal unless they are the same object. For example (JS code, not Japt):

```
var a = [1], b = [1]; alert(a==b); // false
var a = [1], b = a;   alert(a==b); // true

```

If this was not the case, we could remove two bytes by simply not joining each array:

```
Uâ ¦Uw â w

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
ÙIÚÊ

```

Try it online or verify all test cases.

Port of *@xnor*'s Pyth answer.

**Explanation:**

```
Ù       # Uniquified
 IÚ     # Reversed uniquified on the input again
   Ê    # Check if the two lists are not equal

```
> 2 votes

# Answer
## Java, 281 Characters

```
class K{public static void main(String[]a){System.out.println(!k(a[0]).equals(new StringBuffer(k(new StringBuffer(a[0]).reverse().toString())).reverse().toString()));}static String k(String k){for(char i=49;i<58;i++){k=k.replaceFirst(""+i,""+(i-9)).replaceAll(""+i,"");}return k;}}

```
> 1 votes

# Answer
## Python 3, 90 bytes

This function that takes the input as a Python list. Sadly, Python lists don't directly support searching from the end like strings do with `rindex()`, but oh well.

```
def t(c):i,I=c.index,c[::-1].index;return any(i(n)<i(m)and I(n)<I(m)for m in c for n in c)

```
> 1 votes

# Answer
# Jelly, 5 bytes

```
UQU⁻Q

```

Try it online!

Just another port of xnor's answer, so go upvote that.

## How it works

```
UQU⁻Q - Main link. Takes a list l on the left
U     - rev(l)
 Q    - unique(rev(l))
  U   - rev(unique(rev(l)))
    Q - unique(l)
   ⁻  - rev(unique(rev(l)) ≠ unique(l)

```
> 1 votes

---
Tags: code-golf, number, sequence, array, decision-problem
---


title: How many switches are ON

text:
# Question
Title: How many switches are ON
A class has N student and the class room has N switches (all turned OFF and numbered 1 to N). Each student has an enrollment number assigned from 1 to N. Each student serially (by number) toggles the switches that has a number which is divisible by his/her enrollment number.

Example: Student 1 will turn all the switches ON. Student 2 will turn all even switches OFF. Student N just toggles the Nth switch.

Write a function that takes N as input as returns number of ON switches. sample I/O

```
Input: 10
Output:3

```

No upper bound for N is given, but greater the scope, better the code. Shortest and innovative function wins

# Answer
# Python, 19 characters

```
f=lambda n:n**.5//1

```

Perfect squares are the only numbers with an odd number of divisors.

This used to be a **21-character** answer:

```
f=lambda n:int(n**.5)

```

but since I originally wrote it in 2011, the floor-division `//` operator was introduced, which can replace the `int` call.

As a consequence, the answer is now returned as a floating-point number. (But `f(10) == 3.0` is still a correct number of lockers!)
> 16 votes

# Answer
## dc - 5 chars

```
[v]sf

```

Square root in `dc` is `v`. Using stdin/stdout takes 3 chars (`?vp`)
> 11 votes

# Answer
## J, 9 chars

(Just for a simple example on J)

```
f=:[:<.%:

```

floor (`<.`) of square root (`%:`)
> 3 votes

# Answer
# Haskell - 12

Some text so that my post is long enough.

```
f=floor.sqrt

```
> 3 votes

# Answer
# TI-BASIC, 3

```
int(√(Ans

```

Or in **Stuck** (invalid, since it's from 2015):

```
i/)

```

Or in **QWERTY Reverse Polish Notation** (valid, from 2009):

```
@r[

```

Not an interesting answer, but I think they win, since I can't find a language that has either one-character integer square root or implicitly reads from input and performs the calculation in two bytes.
> 2 votes

# Answer
# APL (Dyalog Extended), 2 bytes

```
⌊√

```

Floor of root of the input.

Try it online!, Verify 50 test cases
> 2 votes

# Answer
## GS2, 2 bytes

```
V-

```

The two instructions are parse number, and integer square root, in order.

The reason this works is that the only switches that are on are perfect squares. Those are the only numbers with an odd number of divisors.
> 1 votes

# Answer
# 05AB1E, 2 bytes

Try it online or verify the first `N` test cases.

**Explanation:**

```
t   # Square-root the (implicit) input-integer
 ï  # Cast it to an integer (a.k.a. floors)
    # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Java (JDK), 18 bytes

```
(int)Math.sqrt(n);

```

Try it online!

# Java (JDK), 133 bytes

```
boolean[]a=new boolean[n];
int c,i=c=0;
for(;++i<=n;)
for(int j=0;++j<= n;)
a[j-1]=j%i==0?!a[j-1]:a[j-1];
for(boolean b:a)
c=b?++c:c;

```

Try it online!
> 1 votes

# Answer
# Moonscript 23

Pretty simple and self-explanatory

```
s=(n)->math.floor(n^.5)

```
> 0 votes

# Answer
# Math++, 6 bytes

```
_sqrt?

```

(Filler Text Because 30-char minimum)
> 0 votes

# Answer
# Wren, 23 bytes

Basically square-root and floor.

```
Fn.new{|x|x.sqrt.floor}

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-p`, 9 bytes

```
$_=0|sqrt

```

Try it online!
> 0 votes

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


title: Bake me a cake!

text:
# Question
Title: Bake me a cake!
This is a cake:

```
_========_
|        |
+________+
|        |
+________+
|        |
+________+

```

It is 8 wide, 3 tall, and 1 deep.

You must write a program that makes a cake from 3 inputs. The first input controls how many underscores there are in the middle and `=`s on the top. Here's the first cake with a width of 10 instead of 8:

```
_==========_
|          |
+__________+
|          |
+__________+
|          |
+__________+

```

The second input controls how tall the cake is. Here's the second cake with a height of 4 instead of 3:

```
_==========_
|          |
+__________+
|          |
+__________+
|          |
+__________+
|          |
+__________+

```

Note the repetition of the layers.

The third input controls how deep it is. That just how many `| |`s to include on the top. Here's the third cake with a depth of 2 instead of 1:

```
_==========_
|          |
|          |
+__________+
|          |
+__________+
|          |
+__________+
|          |
+__________+

```

You can print trailing whitespace. Test cases:

Input: `3`, `3`, `3`

Output:

```
_===_
|   |
|   |
|   |
+___+
|   |
+___+
|   |
+___+

```

(I hope I never get this cake)

Input: `3`, `2`, `1`

Output:

```
_===_
|   |
+___+
|   |
+___+

```

Input: `5`, `5`, `5`

Output:

```
_=====_
|     |
|     |
|     |
|     |
|     |
+_____+
|     |
+_____+
|     |
+_____+
|     |
+_____+
|     |
+_____+

```

# Answer
# , ~~25~~, 20 bytes

```
2é_Àé=ÙÒ|èÙÒ+È_ÀäkÀÄ

```

Try it online!

Hexdump:

```
00000000: 32e9 5fc0 e93d d9d2 7ce8 d9d2 2bc8 5fc0  2._..=..|...+._.
00000010: e46b c0c4                                .k..

```

Thanks to *@nmjmcman101* for saving three bytes, and reminding me of an old operator that saved another two bytes.

Explanation:

`a`, `b`, and `c` are the three arguments.

```
2é_                   " Insert two '_' characters
   Àé=                " Insert 'a' '=' characters between them
      Ù               " Duplicate this line
       Ò|             " Replace this whole line with '|'s
         è            " *Hollow* this line (replace all the middle characters with spaces)
          Ù           " Duplicate this line
           Ò+         " Replace this whole line with '+'s
             È_       " *Hollow* this line again, but use '_' instead of spaces
               Àäk    " Make 'b' copies of this line and the line above it
                  ÀÄ  " Make 'c' copies of this line

```
> 9 votes

# Answer
# Charcoal, ~~34~~ 26 bytes

```
Ｎγ←×γ_↑+↑Ｎ_×γ=‖ＢＯγＦ⁻Ｎ¹Ｃ⁰±²

```

Try it online! Link is to verbose version of code. Takes parameters in the order width, depth, height. Explanation:

```
Ｎγ          Input the width.
←×γ_        Print a set of _s that go at the bottom of each layer.
↑+          Print one of the +s that go on the left.
↑Ｎ          Input the depth and print that many left |s.
_           Print the top left _.
×γ=         Print the =s along the top.
‖ＢＯγ        Copy the left column to the right.
Ｆ           Repeat:
 ⁻ ¹         One time fewer than:
  Ｎ           Input of the height:
    Ｃ⁰±²        Copy the whole cake up 2 characters.

```
> 4 votes

# Answer
# 05AB1E, ~~33~~ 31 bytes

```
'_'=¹×«Ć,'|¹úRĆ³G=}²F='+'_¹×«Ć,

```

Try it online!

## Explanation

```
'_'=¹×«Ć,'|¹úRĆ³G=}²F='+'_¹×«Ć,   Full program
'_                                Push literal '_'
  '=¹×                            Push '=' w times
      «Ć,                         Concat, enclose and print
         '|                       Push literal '|'
           ¹ú                     Pad with w spaces in front
             RĆ                   Reverse and ecnlose
               ³G }               d - 1 times do:
                 =                Print without consuming
                   ²F             h times do:
                     =            Print without consuming
                      '+          Push literal '+'
                        '_¹×      Push '_' w times
                            «Ć,   Concat, enclose and print

```
> 3 votes

# Answer
# PHP\>=7.1, 104 Bytes

```
for([,$w,$h,$t]=$argv;$i<2*$h+$t;)echo str_pad($e="_|+"[$b=$i++<$t?$i>1:1+$_++%2],$w+1,"= _"[$b])."$e
";

```

Online Version
> 2 votes

# Answer
## Mathematica, 167 bytes

```
c=Column;r=Row;t=Table;f=Flatten;c[c/@{r/@f[{{{"_",r@t["=",#],"_"}},t[{"|",r@t[" ",#],"|"},#3-1]},1],c/@f[{t[{r@{"|",r@t[" ",#],"|"},r@{"+",r@t["_",#],"+"}},#2]},1]}]&

```
> 2 votes

# Answer
# Jelly, ~~30~~ 29 bytes

-1 byte switching from an addition to an XOR to translate between outer and inner columns, allowing for a 5 character lookup rather than having two `_` entries.

```
ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y

```

Full program taking three program arguments of `depth`, `height`, `width` and printing the cake.

**Try it online!**

### How?

```
ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y - Main link: depth, height (width is a program argument)
Ṭ                             - untruth   [0,0,0,...1] such that the length is the depth
 Ṛ                            - reverse   [1,0,0,...0]
        ¤                     - nilad followed by link(s) as a nilad:
   ⁹                          -   link's right argument, height
    R                         -   range   [1,2,3,...,height]
     Ḥ                        -   double  [2,4,6,...,2*height]
      Ṭ                       -   untruth [0,1,0,1,0,1,...,0,1] (length double height)
       Ḥ                      -   double  [0,2,0,2,0,2,...,0,2]
  ;                           - concatenate  [1,0,0,...,0,0,2,0,2,0,2,...,0,2]
                              -     ...this is the form of a column of cake!
         W                    - wrap in a list
          µ                   - monadic chain separation, call that c
           ^9                 - bitwise XOR c with 9 [8,9,9,...,9,9,11,9,11,9,11,...,9,11]
              ⁵               - program's 3rd argument, width
             ẋ                - repeat the augmented c width times
               ;@             - concatenate with a copy of c
                 ;            - concatenate a copy of c
                  µ           - monadic chain separation call that sideways cake
                   Z          - transpose the sideways cake to put it the right way up
                     “_+= |”  - literal ['_','+','=',' ','|'] (cake decoration)
                    ị         - index into (1 based and modular, so 8,9, and 11 are, mod 5,
                                            3, 4, and 1 yielding '=', ' ', and '_')
                            Y - join with new lines
                              - implicit print

```
> 2 votes

# Answer
# Ruby, 62 bytes

```
->w,h,d{l="|#{' '*w}|
";"_#{?=*w}_
"+l*~-d+(l+"+#{?_*w}+
")*h}

```

Try it online!
> 2 votes

# Answer
# Haskell, 87 bytes

```
f w t d=["_=| +_\n"!!j|i<-0:([2..d]>>[2])++([1..t]>>[2,4]),j<-i:([1..w]>>[i+1])++[i,6]]

```
> 2 votes

# Answer
# Japt, ~~51~~ 47 bytes

```
"_{ç'=}_"+WçA="
|{ç}|" +(B="
+{ç'_}+" +(´V çA+B

```

Try it online!

Input is taken in the order width, height, depth.
> 1 votes

# Answer
# Python 2, ~~124~~ ~~122~~ ~~120~~ ~~105~~ 92 bytes

```
w,t,d=input()
a="\n|"+w*" "+"|"
print"_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+")

```

-15 bytes by using STDIN instead of program arguments

-13 bytes by switching to Python 2 (for `input()`ing integers and `print` statement)

-12 bytes from Caird Coinheringaahing

Try it online!

# Python 3, ~~124~~ ~~122~~ ~~120~~ 105 bytes

```
w,t,d=[int(input())for n in(1,2,3)]
a="\n|"+w*" "+"|"
print("_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+"))
```

Try it online!

If a full program is not required:

# Python 3, ~~87~~ 84 bytes

```
lambda w,t,d:"_"+w*"="+"_"+(d-1)*("\n|"+w*" "+"|")+t*("\n|"+w*" "+"|\n+"+w*"_"+"+")
```

Try it online!
> 1 votes

# Answer
# dc, 108 bytes

```
?sdstsw95P61sc[lwsf[lcPlf1-dsf0<a]dsax]dsbx[_]p[[124P32sclbx[|]pld1-dsd0<j]dsjx43P95sclbx[+]plt1-dst0<h]dshx

```

Try it online!
> 1 votes

# Answer
# Röda, 65 bytes

```
a,b,c{d=" "*a;[`_${"="*a}_
`,`|$d|
`*(c-1),`|$d|
+${"_"*a}+
`*b]}

```

Try it online!
> 1 votes

# Answer
# Windows Batch, ~~211 180~~ 163 bytes

Golfed a total of ***48 bytes*** thanks to @Neil!

```
@for /l %%p in (1,1,%1)do @call set w= %%w%%
@echo _%w: ==%_
@for /l %%p in (2,1,%3)do @echo ^|%w%^|
@for /l %%p in (1,1,%2)do @echo ^|%w%^|&echo +%w: =_%+
@set w=

```
> 1 votes

# Answer
# Java 7, ~~169~~ ~~164~~ 158 bytes

```
String f(int...a){String s="_",t="|",u="+";for(;a[0]-->0;s+="=",t+=" ")u+="_";s=s+"_";t="\n"+t+"|";u=t+"\n"+u+"+";for(;a[2]-->1;)s+=t;for(;a[1]-->0;)s+=u;return s;}

```

Try it online!

Ungolfed:

```
String f(int...a)                    // saves two bytes over int a, int b, int c
{
    String s="_", t="|", u="+";      // set up the start of each row

    for(; a[0]-->0; s+="=", t+=" ")  // Uses the goes-to operator to fill the row
        u+="_";

    s += "_\n";                      // adds the end of each row
    t += "|\n";
    u = t + u + "+\n";               // and combining t into u

    for(; a[2]-->1; )                // add the top of the cake
        s += t;

    for(; a[1]-->0; )                // add the rest of the cake
        s += u;

    return s;
}

```
> 1 votes

# Answer
# SOGL V0.12, 25 bytes

```
e =*¼_Oe↕¼|.⌡Qe╔*¼+.H«{Q;

```

Try it Here!

Expects the input as width, depth, then height.
> 1 votes

# Answer
# Javascript (ES6), ~~161~~ 157 bytes

```
f=(w,h,d)=>{r=x=>x.repeat(w);_='_';m='+'+r(_)+'+';b='|'+r(' ')+'|';c=[_+r('=')+_];for(i=d-1;i--;)
c.push(b);for(i=h;i--;)
c.push(b+'\n'+m);return c.join`\n`}

console.log(f(8,3,1));
```
> 0 votes

# Answer
# Python 2, 93 bytes

```
i,j,k=input()
l=["|"+" "*i+"|"]
for x in["_"+"="*i+"_"]+l*(k-1)+(l+["+"+"_"*i+"+"])*j:print x

```

Try it online!
> 0 votes

# Answer
# Perl 5, 85 + 1 (-a) = 86 bytes

```
say"_".'='x($w=$F[0])."_\n".($l='|'.$"x$w."|\n")x($F[2]-1).("$l+".'_'x$w."+\n")x$F[1]

```

Try it online!
> 0 votes

# Answer
# JavaScript/ES6, 90 bytes

I just wrote a rough solution, and happened to beat the existing JS answer by a whopping 56 bytes. Then I golfed off 11 bytes.

```
(w,h,d,g=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>g('_=')+(l=g('| '))[r](d-1)+(l+g('+_'))[r](h)

```

Here's a demo.

```
var F = (w,h,d,f=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>f('_=')+(l=f('| '))[r](d-1)+(l+f('+_'))[r](h);

console.log(F(prompt('width') || 3, prompt('height') || 3, prompt('depth') || 3));
console.log(F.toString().length);
```
> 0 votes

# Answer
# Canvas, 23 bytes

```
|＊_⁷⇵×+×∔║│Ｐ
=×_ｅＰ⁸╷｛１⁸

```

Try it here!
> 0 votes

# Answer
## Google Sheets, 89

Inputs A1, A2, A3.

* A4 - `_`
* A5 - (Discount 1 for `"`)
```
="|"&REPT(" ",A1)&"|
"

```

Final output (Discount 1 for `)`):

```
=A4&REPT("=",A1)&"_
"&REPT(A5,A3-1)&REPT(A5&"+"&REPT(A4,A1)&"+
",A2)

```
> 0 votes

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


# Question
Title: Minimal Rotate-Right-Double numbers in base n
## Task

For a given base \\$n \ge 3\\$, find the smallest positive integer \\$m\\$, when written in base \\$n\\$ and rotated right once, equals \\$2m\\$. The base-\\$n\\$ representation of \\$m\\$ cannot have leading zeroes.

The corresponding OEIS sequence is A087502, and its base-\\$n\\$ representation is A158877 (this one stops at \\$n=11\\$ because the answer for \\$n=12\\$ has a digit higher than 9). The OEIS page has some information about how to calculate the number:

> `a(n)` is the smallest integer of the form `x*(n^d-1)/(2n-1)` for integer `x` and `d`, where `1 < x < n` and `d > 1`. `x` is the last digit and `d` is the number of digits of `a(n)` in base `n`.
>
> Maple code:
>
> ```
> A087502 := proc(n) local d, a; d := 1; a := n; while a>=n do
>   d := d+1; a := denom((2^d-1)/(2*n-1)); od;
> return(max(2, a)*(n^d-1)/(2*n-1)); end proc;
>
> ```

You may output the result as a single integer or a list of base-10 or base-\\$n\\$ digits.

## Examples and test cases

For \\$ n = 3 \\$, the answer is \\$ m = 32 \\$. \\$ n = 4 \\$ should give \\$ m = 18 \\$.

$$ m = 32\_{10} = 1012\_3 \rightarrow 2m = 64\_{10} = 2101\_3 \\ m = 18\_{10} = 102\_4 \rightarrow 2m = 36\_{10} = 210\_4 $$

```
n = 3
m = 32
m (base n) = 1012 or [1,0,1,2]
------------------------------
n = 4
m = 18
m (base n) = 102 or [1,0,2]
------------------------------
n = 10
m = 105263157894736842
m (base n) = 105263157894736842 or [1,0,5,2,6,3,1,5,7,8,9,4,7,3,6,8,4,2]
------------------------------
n = 33
m = 237184
m (base n) = 6jqd or [6,19,26,13]
------------------------------
n = 72
m = 340355112965862493
m (base n) = [6,39,19,45,58,65,32,52,26,13]

```

More I/O examples can be found on OEIS.

## Scoring and winning criterion

Standard rules apply. Shortest solution in bytes wins.

# Answer
> 3 votes
# Python 2, ~~77~~ ~~76~~ 70 bytes

```
f=lambda n,m=1,i=1:i<m and f(n,m,i*n)or(m+m%n*i)/n-m*2and f(n,m+1)or m

```

Try it online!

**Input**: base `n`
**Output**: The smallest integer `m` satisfies the requirement.

*Saved 6 bytes thanks to @Bubbler!*

This is a brute-force search that starts at `m = 1` and works its way up. Will run out of recursion limit if the actual solution is too large.

For each `m`, `i` keeps track of the current power of `n`, which is increased until `i>m`.

# Answer
> 3 votes
# JavaScript (ES7),  ~~90 88 86~~  85 bytes

A recursive port of the Maple function.

```
n=>(d=1,x=n,g=(a=2**++d-1,b=q=n+~-n)=>b?g(b,a%b):(x=q/a)<n?(x+!~-x)*(n**d-1)/q:g())()

```

Try it online! (\\$a(3)\\$ to \\$a(9)\\$)

Or, for +5 bytes, a BigInt version:

```
n=>(d=1n,x=n,g=(a=2n**++d-1n,b=q=n+~-n)=>b?g(b,a%b):(x=q/a)<n?(~-x?x:2n)*~-(n**d)/q:g())()

```

Try it online! (\\$a(3)\\$ to \\$a(50)\\$)

# Answer
> 3 votes
# 05AB1E, ~~15~~ 11 bytes

```
∞.ΔxsIвÁIβQ

```

-4 thanks to @Grimmy

Try it online!

explanation:

```
∞ get all positive numbers
 .Δ find the first number for which:
   xs the number doubled and itself (e.g. 64, 32)
     Iв convert to base input (e.g. [1, 0, 1, 2])
       Á rotate right (e.g. [2, 1, 0, 1])
        Iβ convert back from base input to a number (e.g. 64)
          Q compare to the number doubled (that's in the stack from xs)

```

# Answer
> 2 votes
# Japt, 11 bytes

```
_Ñ¶ZsU'é}a1

```

Try it

```
_Ñ¶ZsU'é}a1     :Implicit input of integer U
_               :Function taking an integer Z as an argument
 Ñ              :  Multiply by 2
  ¶             :  Check for equality with
   ZsU          :  Convert Z to a string in base U
      'é        :    Rotate right (string is converted back to decimal afterwards)
        }       :End function
         a1     :Starting with 1, return the first integer that returns true when passed through that function

```

The `'` trick prevents the `é` method from being applied to U (sidenote: there *is* no `é` method for numbers in Japt), instead applying it to the base-U string, and saves 2 bytes over the alternative `ZsU,_éÃ`.

# Answer
> 1 votes
# Python 2, 78 bytes

Simple direct solution. Increments `x` and `d` until we obtain the appropriate answer.

```
n=input()
j=x=d=2;k=2*n-1
while j%k:j=x*n**d-x;x=[2,x+1][x<n];d+=x<3
print j/k

```

Try it online!

# Answer
> 1 votes
# Bash \+ bc, 103 bytes

```
for((m=1;2*m!=p;));do((m++));t=$(bc<<<"obase=$1;$m");p=$(bc<<<"ibase=$1;${t: -1}${t::-1}");done;echo $m

```

Try it online!

# Answer
> 1 votes
# Pyth, 30 bytes

```
Fdr2Kt*2QVr2hQI!%J*Nt^QdK/JK.q

```

Try it online!

Uses a similar approach to my Python 2 answer. **Note:** I also used the upper bound of 2n-2 on `d` that @Bubbler mentioned in a comment.

```
(Q)

```

Implicitly initialize Q to be the input

```
Kt*2Q

```

Initialize K to be 2Q-1

```
Fdr2K

```

For d in range(2, 2Q-1):

```
Vr2hQ

```

\- For N in range(2, Q+1):

```
J*Nt^Qd

```

--\> Set J to N * (Q^d - 1)

```
I!%JK/JK.q

```

--\> If J%K==0, print J/K and exit the program

# Answer
> 0 votes
# Charcoal, 41 bytes

```
Ｎθ≔⊖⊗θηＩ÷⌊ΦＥ×θη∨‹ι⊗θ∨‹﹪ιθ²×﹪ιθ⊖Ｘθ÷ιθ¬﹪ιηη

```

Try it online! Link is to verbose version of code. Uses the OEIS quote plus the additional information provided by @Bubbler in a comment whereby `d < 2n-1`. Explanation:

```
Ｎθ

```

Input `n`.

```
≔⊖⊗θη

```

Calculate `2n-1`.

```
Ｅ×θη

```

Loop `nd + x` from `0` to `n(2n-1)`.

```
∨‹ι⊗θ

```

Ensure `d > 1` by returning `1` if it is not, which is never divisible by `2n-1`.

```
∨‹﹪ιθ²

```

Ensure `x > 1` in the same way.

```
×﹪ιθ⊖Ｘθ÷ιθ

```

Calculate `x(nᵈ-1)`.

```
Φ...¬﹪ιη

```

Keep only those values that are multiples of `2n-1`.

```
Ｉ÷⌊...η

```

Divide the minimum of those values by `2n-1` and output the result.

# Answer
> 0 votes
# Scala, 80 bytes

```
n=>Stream.iterate(1)(n*_)map(p=>p to p*n-1 find(x=>2*x==x%n*p+x/n))find(_!=None)

```

Try it online!

Takes an integer n, returns an `Option[Option[Int]]` (really a `Some[Some[Int]]`).

---
Tags: code-golf, sequence, base-conversion
---


title: Fibonacci products

text:
# Question
Title: Fibonacci products
You can decompose a number greater than 0 as a unique sum of positive Fibonacci numbers. In this question we do this by repeatedly subtracting the **largest possible** positive Fibonacci number. E.g.:

```
1 = 1
2 = 2
3 = 3
4 = 3 + 1
12 = 8 + 3 + 1
13 = 13
100 = 89 + 8 + 3

```

Now, I call a *Fibonacci product* the same lists as above, but with the addition replaced by multiplication. For example, \\$f(100) = 89 \times 8 \times 3 = 2136\\$.

Write a program or function that given a positive integer *n* returns the Fibonacci product of that number.

---

Testcases:

```
1: 1
2: 2
3: 3
4: 3
5: 5
6: 5
7: 10
8: 8
9: 8
42: 272
1000: 12831
12345: 138481852236

```

# Answer
> 5 votes
# Jelly, ~~16~~ 15 bytes

```
Rf1+Ð¡¤ṪạµÐĿIAP

```

Not particularly fast or memory friendly, but efficient enough for all test cases. Try it online!

### How it works

```
Rf1+Ð¡¤ṪạµÐĿIAP  Main link. Argument: n (integer)

         µ       Combine the chain to the left into a link.
          ÐĿ     Apply that link until the results are no longer unique.
                 Return the list of unique results.
      ¤            Combine the two links to the left into a niladic chain.
  1                  Set the left (and right) argument to 1.
   +D¡               Apply + to the left and right argument, updating the left
                     argument with the sum, and the right argument with the
                     previous value of the left one. Return the list of results.
                     Repeat this process n times.
                   This yields n + 1 Fibonacci numbers, starting with 1, 2.
R                  Range; map k to [1, ..., k].
 f                 Filter; keep the items in the range that are Fibonacci numbers.
       Ṫ           Tail; yield the last one or 0 if the list is empty.
        ạ          Absolute difference with k.
                   This is the argument of the next iteration.
            I    Compute the increments of the arguments to the loop, yielding
                 the selected Fibonacci numbers (with changed sign).
             A   Apply absolute value to each.
              P  Compute their product.

```

# Answer
> 9 votes
## Python, 54 bytes

```
f=lambda n,a=1,b=1:n<1or b>n and a*f(n-a)or f(n,b,a+b)

```

Just some good old recursion.

# Answer
> 5 votes
# Perl, ~~69~~ 63 + 4 (`-pl61` flag) = 67 bytes

```
#!perl -pl61
while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{

```

Using:

```
> echo 42 | perl -pl61e 'while($_){$n=$m=1;($n,$m)=($m,$n+$m)until$m>$_;$_-=$n;$\*=$n}}{'

```

Ungolfed:

```
while (<>) {
# code above added by -p
    # $_ has input value
    # $\ = 1 by -l61
    while ($_ != 0) {
        my $n = 1;
        my $m = 1;
        while ($m <= $_) {
            ($n, $m) = ($m, $n + $m);
        }
        $_ -= $n;
        $\ *= $n;
    }
} {
# code below added by -p
    print;  # prints $_ (undef here) and $\
}

```

Ideone.

# Answer
> 2 votes
# \>\<\>, 57 bytes

```
111\ ;n{/
:@+>:{:})?\$:@@
~{*}:0=?\}>:0${:})?$~:{$-$:1@?$

```

Expects the input number to be present on the stack at program start.

Builds up the Fibonacci sequence (`f0, f1, f2, ..., fn`) on the stack until a number is reached that is greater than the the input (`i`). Then, with a product (`p`) initialised to `1`...

```
while (i != 0)
   if (fn <= i)
      i = i - fn
      p = p * fn
   else
      i = i - 0
      p = p * 1
   discard fn
output p

```

Try it out online!

# Answer
> 2 votes
## JavaScript (ES6), ~~78~~ 42 bytes

```
f=(n,a=1,b=1)=>n?b>n?a*f(n-a):f(n,b,a+b):1

```

Port of @Sp3000's answer. Original 78 byte version:

```
f=(n,a=[2,1])=>n>a[0]?f(n,[a[0]+a[1],...a]):a.map(e=>e>n?0:(r*=e,n-=e),r=1)&&r

```

# Answer
> 2 votes
# Haskell, 44 bytes

Yay for mutual recursion:

```
(a&b)c|c<1=1|b>c=a*f(c-a)|d<-a+b=b&d$c
f=0&1

```
* `a` is the previous Fibonacci number
* `b` is the current Fibonacci number
* `c` is the input
* `f` is the desired function

Less golfed:

```
(a & b) c | c == 0    = 1
          | c <  b    = a * f (c-a)
          | otherwise = b & (a + b) $ c
f x = (0 & 1) x

```

# Answer
> 2 votes
# Jelly, 10 bytes

```
ŒṗḟÐḟÆḞ€ṪP

```

Try it online!

Times out for \\$n \> 60\\$

## How it works

```
ŒṗḟÐḟÆḞ€ṪP - Main link. Takes n on the left
Œṗ         - Integer partitions of n
     ÆḞ€   - First n Fibonacci numbers
   Ðḟ      - Keep the partitions p which yield an empty list under:
  ḟ        -   Remove all elements of p which are in the first n Fibonacci numbers
        Ṫ  - Take the last element
         P - Product

```

# Answer
> 1 votes
# Pyth, 28 bytes

```
K1WQJ0 .WgQH+Z~JZ1=*KJ=-QJ;K

```

I think it can be golfed much further...

Try it online!

# Answer
> 1 votes
# Javascript (ES6) ~~134~~ ~~106~~ 92 bytes

Thanks for @cat for spotting a space.

```
n=>{for(c=[a=b=s=1,1];a+b<=n;)a+=b,c.unshift(b+=a,a);c.map(i=>i<=n&&(n-=i)&(s*=i));alert(s)}

```

Just an unoptimized version made on my phone, I golf it down, once I get home. Ideas are welcome.

# Answer
> 1 votes
# Pyth, 24 bytes

```
W=-QeaYh.WgQeH,eZsZ1;*FY

```

Try it online: Demonstration or Test Suite

### Explanation:

`Q` is assigned with the input number.

The part `h.WgQeH,eZsZ1` calculates the biggest Fibonacci number, that is smaller or equal to `Q`

```
h.WgQeH,eZsZ1
            1   start with H=Z=1
 .WgQeH         while Q >= end(H):
       ,eZsZ       H=Z=(end(Z), sum(Z))
h               first

```

So if `Q = 10`, it generates the numbers/pairs:

```
1 -> (1,1) -> (1,2) -> (2,3) -> (3,5) -> (5,8) -> (8,13) -> 8

```

The rest of the code calculates the partition and multiplies the numbers together:

```
W=-QeaY...;*FY    implicit: Y = empty list
     aY...        add the calculated Fibonacci number to the empty list
    e             take the last element of Y (yes the number we just added)
 =-Q              and update Q with the difference of Q and ^
W         ;       continue until Q == 0
           *FY    multiply all number in Y and print

```

There are obviously a lot of shorter solutions (with really bad run-times though), like `*FhfqQsTyeM.u,eNsNQ1`.

# Answer
> 1 votes
## Actually, 22 bytes

```
W;╗uR♂F;`╜≥`M░M;╜-WXkπ

```

Try it online!

Explanation:

```
W;╗uR♂F;`╜≥`M░M;╜-WXkπ
                        (implicit input)
W                 W     while top of stack is truthy:
 ;╗                       push a copy of n to reg0
   uR♂F;                  push 2 copies of [Fib(a) for a in range(1, n+2)]
        `╜≥`M░            filter: take values where n <= Fib(a)
              M;          two copies of maximum (call it m)
                ╜-        subtract from n (this leaves n-m on top of the stack to be the new n next iteration, with a copy of m below it)
                   X    discard the 0 left over after the loop ends
                    kπ  product of all stack values

```

# Answer
> 1 votes
# RETURN, 44 bytes

```
[a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#]

```

`Try it here.`

Astonishingly inefficient anonymous lambda that leaves result on Stack2. Usage:

```
12345[a:[a;][1$[¤¤+$a;->~][]#%$␌a;\-a:]#␁[¤][×]#]!

```

NOTE: ␌ and ␁ are placeholders for their respective unprintable chars: Form Feed and Start of Heading.

# Explanation

```
[                                           ]  lambda
 a:                                            store input to a
   [  ][                         ]#            while loop
    a;                                           check if a is truthy
        1$[¤¤+$a;->~][]#%                        if so, generate all fibonacci numbers less than a
                         $␌                      push copy of TOS to stack2
                           a;\-a:                a-=TOS
                                   ␁[¤][×]#   get product of stack2

```

# Answer
> 1 votes
# PHP, 119 bytes

The code (wrapped on two lines for readability):

```
for($o=$c=1;$c<=$n=$argv[1];$f[++$k]=$c,$a=$b,$b=$c,$c+=$a);
for($i=$k;$i;$i--)for(;$n>=$d=$f[$i];$n-=$d,$o*=$d);echo$o;

```

The first line computes in `$f` the Fibonacci numbers smaller than `$n` (the argument provided in the command line). The second line computes the Fibonacci factors (by subtraction) and multiplies them to compute the product in `$o`.

Prepend the code with `<?php`  (technically not part of the program), put it in a file (`fibonacci-factors.php`) then run it as:

```
$ php -d error_reporting=0 fibonacci-factors.php 100
# The output:
2136

```

Or run it using `php -d error_reporting=0 -r '... code here ...' 100`.

The ungolfed code and the test suite can be found on Github.

# Answer
> 1 votes
## Q, 47 Bytes

```
m:{*/1_-':|(0<){y-x x bin y}[*+60(|+\)\1 0]\x}

```

**Test**

```
+(i;m'i:1 2 3 4 5 6 7 8 9 42 1000 12345)

```

read it as pairs (i,map(m,i)), where m is the calculating function and i the different args

writes

```
1     1
2     2
3     3
4     3
5     5
6     5
7     10
8     8
9     8
42    272
1000  12831
12345 138481852236

```

**Explanation**

`n funtion\arg` applies function(function(function(...function(args))) n times (internally uses tal recursion), and returns the sequence of results. We calculate the 60 first items of fibonnaci series as `*+60(|+\)\1 0`. In that case the function is (|+): +\ applied over a sequence calculates partial sums (ex +\1 2 3 is 1 3 6), and | reverses seq. So each 'iteration' we calculate partial sums of the two previous fibonacci number and return the partial sums reversed. `60(|+\)\1 0` generates sequences 1 0, 1 1, 2 1, 3 2, 5 3, 8 5, 13 8, 21 13, ... `*+` applied over this result flip (traspose) it and takes the first. Result is sequence 1 1 2 3 5 8 13 21 34 55 ..

`(cond)function\args` applies function(function(..function(args))) while cond true, and returns the sequence of partial results

`function[arg]` applied over a function of more than one argument creates a projection (partial application)

We can give name to the args, but the implicit names are x,y,z

`{y-x x bin y}[*+60(|+\)\1 0]` declares a lambda with args x,y with partial projection (arg x is fibonacci series, calculates as \*+60(|+)\1 0). x represent fibonacci values, and y the number to process. Binary search (bin) is used to locate the index of the greater fibonacci number \<=y (`x bin y`), and substract the corresponding value of x.

To calculate product from partial resuls we reverse them and calculate difference of each pair (`-':|`), drop the first (`1_` because is 0) and multiply over (`*/`).

If we are interested in accumulated sum the code is the same, but with `+/` instead of `*/`. We can also use any other diadic operator instead of + or *

**About execution efficiency**

I know that in this contest efficiency is not an issue. But in this problem we can range from lineal cost to exponential cost, so i'm curious about it.

I developed a second version (length 48 Bytes excluding comment) and repeated test cases battery 1000 times on both versions.

```
f:*+60(|+\)\1 0;m:{*/1_-':|(0<){x-f f bin x}\x}    /new version

```

execution time is: original version 0'212 seg, new version 0'037 seg

Original version calculates fibbonaci serie once per function application; new version calculates fibonacci just one.

In both cases calculation of fibonacci series uses tail recursion

---
Tags: code-golf, math, sequence, fibonacci
---


title: Simplification of numbers

text:
# Question
Title: Simplification of numbers
How, you can’t remember the 6 or 7-digit phone number that appeared on the TV screen for a second?! Using the special technique described below, you will turn into a walking phonebook!

Obviously, the number `402` is easier to remember than the number `110010010`, and the number `337377` is easier to remember than the number `957472`. This means that the memorized number, on the one hand, should contain as few digits as possible, and on the other hand, it is desirable that the number contains as many repeating numbers as possible.

As a criterion for the difficulty of remembering, we take the sum of the number of digits in number and the number of different digits in number. A memorized number can be written in another number system, perhaps then it will be easier to remember. For example, the number `65535` in the hexadecimal notation looks like `FFFF`.

## Task

You need to write a program for selecting the base of the number system to minimize the complexity criterion. The base of the number system must be selected in the range from 2 to 36, then the numbers `0-9` and the English letters `A-Z` can be used to represent the number.

## Input

The input contains a decimal integer from 1 to 999999999.

## Output

The output must contain the base of the number system (from 2 to 36), minimizing the criterion of memorization complexity, and the number in the selected number system, separated by one space. If several bases give the same value for the criterion, then choose the smallest among them.

## Notes

* The letters must be uppercase(`A-Z`).

## Test Cases

### Input Output

`1` `2 1`

`2` `3 2`

`65535` `16 FFFF`

`123` `12 A3`

# Answer
# Perl 6, ~~55~~ 54 bytes

*-1 byte thanks to Jo King.*

```
{~map({$^b,.base($b)},2..36).min:{@$_+.Set}o*[1].comb}

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~150~~ ~~149~~ ~~127~~ 144 bytes

```
lambda n:min((len(c(n,b))+len(set(c(n,b))),b,c(n,b))for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n/b,b,chr(n%b+48+7*(n%b>9))+s)or s or'0'

```

Try it online!

---

# Python 3, 136 bytes

```
lambda n:min((len((*c(n,b),*{*c(n,b)})),b,c(n,b))for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n//b,b,chr(n%b+48+7*(n%b>9))+s)or s

```

Try it online!

---

# Python 3.8 (pre-release), 131 bytes

```
lambda n:min((len((*(x:=c(n,b)),*{*x})),b,x)for b in range(2,37))[1:]
c=lambda n,b,s='':n and c(n//b,b,chr(n%b+48+7*(n%b>9))+s)or s

```

Try it online!

---

`c` converts a base 10 number to any base (2-36), and the first (anonymous) function finds the smallest result.
> 5 votes

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

*-1 byte thanks to Kevin Cruijssen*

```
₆LBāøΣнDÙìg}1è

```

Try it online!

Or add R)» at the end to conform exactly to the specified output format, but most other answers didn't bother.

Explanation:

```
₆L          # range 1..36
  B         # convert the input to each of those bases
   āø       # enumerate (pair each element with its 1-based index)
Σ     }     # sort by
     g      # length
 н          # of the first element
    ì       # concatenated to
  DÙ        # itself, uniquified
1è          # take the second entry (first will always be base 1)

```
> 5 votes

# Answer
# JavaScript (ES6),  ~~87 85~~  101 bytes

*Edit: +16 useless bytes to comply with the strict output format*

```
n=>(g=m=>--b>2?g(m<(v=new Set(s=n.toString(b)).size+s.length)?m:(o=b+' '+s.toUpperCase(),v)):o)(b=37)

```

Try it online!
> 4 votes

# Answer
# Japt v2.0a0 `-gS`, ~~24~~ 23 bytes

Not pretty, but it does the job. +2 bytes for the completely unnecessary requirement that output be uppercase.

```
37o2@sX u ¸iXÃñÈÌiXÌâ)l

```

Try it

```
37o2@sX u ¸iXÃñÈÌiXÌâ)l     :Implicit input of integer
37o2                        :Range [2,37)
    @                       :Map each X
     sX                     :  Convert the input to a base-X string
        u                   :  Uppercase
          ¸                 :  Split on spaces (there are none, so this returns a singleton array)
           iX               :  Prepend X
             Ã              :End map
              ñ             :Sort by
               È            :Pass each X through the following function
                Ì           :  Last element of X
                 i          :  Prepend
                  XÌâ       :    Last element of X, deduplicated
                     )      :  End prepend
                      l     :  Length
                            :Implicit output of the first sub-array, joined with spaces

```
> 4 votes

# Answer
# PHP, ~~124~~ 119 bytes

```
for($i=36;$b=strtoupper(base_convert($argn,10,--$i));$o[strlen($b.count_chars($b,3))]="$i $b");krsort($o);echo end($o);

```

Try it online!

A shame about the **+12** bytes in PHP to uppercase the output... but... anyway.
> 3 votes

# Answer
# Zsh, 85 bytes

```
for b ({36..2})x=$[[#$b]$1]&&x=${x#*\#}&&a[$#x+${#${(us::)x}}]=$b\ $x
a=($a)
<<<$a[1]

```

For this number of statements inside the for loop, using `...&&...&&...` is shorter than `{...;...;...;}`.

```
for b ({36..2})                   # order decreasing: smaller bases overwrite larger ones
    x=$[[#$b]$1] && \             # set x to [base]#[num]
    x=${x#*\#} && \               # strip leading [base]#
    a[$#x+${#${(us::)x}}]=$b\ $x  # use score as index to store "[base] [number]"
#            ${(us::) }           # (s::)plit into characters, take (u)nique
a=($a)                            # remove empty elements from array
<<<$a[1]                          # print out the first element (smallest score)

```

Try it online!

Here's an 81-byte solution which prints in the form `[base]#[num]` instead:

```
for b ({36..2})x=$[[#$b]$1]&&y=${x#*\#}&&a[$#y+${#${(us::)y}}]=$x
a=($a)
<<<$a[1]

```

Try it online!
> 3 votes

# Answer
# , 67 bytes

```
(];'0123456789ABCDEF'{~b)[:(2+]i.<./)](#+#@~.)@(b=:#.inv~)"+2+i.@35

```

Try it online!
> 3 votes

# Answer
# Charcoal, 38 bytes

```
Ｎθ≔ＥＥ³⁴↨θ⁺²ιＬ⁺ιΦι⁼λ⌕ικη≔⁺²⌕η⌊ηηＩη ↥⍘θη

```

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

```
Ｎθ

```

Input the integer.

```
≔ＥＥ³⁴↨θ⁺²ι

```

Convert it from base 2 to base 36...

```
Ｌ⁺ιΦι⁼λ⌕ικη

```

... deduplicate, concatenate, and take the length.

```
≔⁺²⌕η⌊ηη

```

Take the index of the minimum complexity and add 2 to get the base.

```
Ｉη ↥⍘θη

```

Print the base and the integer converted to that base in upper case.
> 2 votes

# Answer
# Stax, 19 bytes

```
Ç╛;ⁿY3█↕(╖S♪*ò▌?½╦l

```

Run and debug it

No fancy algorithm, just straightforward brute force. About a third of the program is format-wrangling for the precise output rules.

Bonus program: Output for \[1..1000\]
> 2 votes

# Answer
# Jelly, 25 bytes

```
bⱮ36µQL+LN)Mḟ1Ḣ,ị‘ịØBʋ¥⁸K

```

Try it online!

A monadic link taking an integer as its argument and returning a Jelly string of the desired format. If a two-item list was acceptable output (as per most challenges), could save 2 bytes. If base 1 were acceptable for the edge case of 1 as input, could save a further 2 bytes.
> 2 votes

# Answer
# Brachylog, 44 bytes

```
∧Y≜∧36≥Xℕ₂≜&ḃ↙X Zd,Zl≡Y∧XwṢwZ{-₁₀;Ạụᵗ∋₍|}ᵐwᵐ

```

Try it online!

This hurt a bit to write.
> 2 votes

# Answer
# Japt v2.0a0, 31 bytes

```
2o37 ñ@sX Ê+UsX â ÊÃÎ
+S+NÎsU u

```

Try it
> 1 votes

# Answer
# Perl 5, 161 bytes

```
sub f{$X=99;for$b(2..36){$_=c($_[0],$b);$x=uniq(/./g)+y///c;($X,$B,$C)=($x,$b,$_)if$x<$X}$B,$C}
sub c{my($n,$b)=@_;$n?c(int$n/$b,$b).chr(48+$n%$b+7*($n%$b>9)):''}

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~109~~ 111 bytes

```
Print[a=OrderingBy[#~IntegerDigits~Range@36,Tr[1^#]+Tr[1^Union@#]&,1][[1]]," ",ToUpperCase[#~IntegerString~a]]&

```

+2: fixed. Thanks for the catch @Roman

`OrderingBy` was introduced in Mathematica 12.0, which TIO does not seem to have updated to yet.
> 1 votes

# Answer
# Python 2, ~~140~~ 135 bytes

```
lambda n:min([(b,g(n,b))for b in range(2,36)],key=lambda(b,s):len(s)+len(set(s)))
g=lambda n,b:n and g(n/b,b)+chr(n%b+48+7*(n%b>9))or''

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-Minteger -MList::Util=uniq,first -ap`, ~~123~~ 112 bytes

```
$"=$,;map{@r=();$t="@F";do{unshift@r,(0..9,A..Z)[$t%$_]}while$t/=$_;$a[@r+uniq@r]||="$_ @r"}2..36;$_=first{$_}@a

```

Try it online!
> 1 votes

# Answer
# C (clang), ~~165~~ 161 bytes

```
j,r,m,x,*_;t(n){for(char*g,b[74][37]={},i=1,p=99;g=b[++i],i<37;r=j<p?_=g,p=j,i:r)for(j=0,m=n;m;m/=i,*--g=x+=x>9?87:48)j-=~!b[i+36][x=m%i]++;printf("%i,%s",r,_);}

```

Try it online!

* Shortened and improved by @ceilingcat

```
n//input

,i=2//iterator from base 2 to 36

,j//current complexity

,p=99//best complexity

,r//result = iterator

,m// temp copy of n

,x ;// m%i

char*g // current string ptr

,*_ // best str ptr

,b[74][37];//buffer

/* [37+37] = [strings obtained +
              test for used characters  ]
*/

t(n){

 for(; g=b[i], // move ptr

       i<37 ;
       r=j<p?_=g,p=j,i:r, // save best solution

       ++i){//for every base

  for( j=0,m=n; m ; m/=i, // extract digit

       *--g=x+=x>9?87:48)
       // move ptr backward for printf use and transform to ascii value

   j+=b[i+36][x=m%i]++?1:2;
   // increment byte relative to the character

   // and if it was 0 increments j by 2 : 1 for the new character used and 1 for digit count

   // else incr only digits count + move pointer

  //printf("%s - ",g);// test

// printf("r%i p%i j%i\n",r,p,j);// test

 }

 printf("%i,%s",r,_);//output

}

```
> 1 votes

# Answer
# Scala, ~~105~~ 97 bytes

```
n=>{val(b,x)=2.to(36)map(b=>b->n.toString(b))minBy((_,x)=>(x++x.toSet).size);b+" "+x.toUpperCase}

```

Try it online!
> 1 votes

---
Tags: code-golf, number, base-conversion
---


title: What logic gates work given the input?

text:
# Question
Title: What logic gates work given the input?
# Introduction

Logic gates! Everyone knows them, everyone loves them (unless you're starting to learn them). Take two booleans, compare them, get a single boolean in return. `AND`, `NAND`, `OR`, `NOR`, `XOR`, `XNOR`. Fun! But, what if you only had the inputs and output, but *not* the operator?

# Challenge

Given a three digit number, `xyz`, where `x` and `y` are inputs to the unknown gate(s) and `z` is the output, list all the possible gates. The output order doesn't matter but it must be all caps and separated by a space. This is , so the shortest answer wins!

# Example Inputs and Outputs

Inputs:

> 001
>
> 101
>
> 111

Outputs:

> NAND NOR XNOR
>
> NAND OR XOR
>
> AND OR XNOR

# Answer
> 10 votes
# JavaScript (ES6),  ~~58~~  56 bytes

```
n=>`25AND 41OR X37OR`.replace(/\d+/g,m=>m>>n%6&1?'':'N')

```

Try it online!

### How?

Given the input \\$n\\$, we compute \\$n\bmod 6\\$ to get an index into 3 small lookup bit masks.

It's worth noting that all operations are commutative, i.e. \\$(X \operatorname{op} Y)=(Y \operatorname{op} X)\\$ even when \\$X=\lnot Y\\$. So the collisions between `011` and `101` and between `010` and `100` are actually very welcome.

```
 n (decimal) | n mod 6 | NAND | NOR | XNOR
-------------+---------+------+-----+------
  011 or 101 |    5    |   0  |  1  |  1
  010 or 100 |    4    |   1  |  0  |  0
         111 |    3    |   1  |  1  |  0
         110 |    2    |   0  |  0  |  1
         001 |    1    |   0  |  0  |  0
         000 |    0    |   1  |  1  |  1
                           |     |     |
                           |     |     +--> 0b100101 = 37
                           |     +--------> 0b101001 = 41
                           +--------------> 0b011001 = 25

```

We look for the bit masks in the string `"25AND 41OR X37OR"` and replace them with either `"N"` or an empty string.

# Answer
> 4 votes
# Jelly, 33 bytes

```
V€Ḅ“n|ḃ’b⁹¤æ»ị“N“”ż“AND “OR X“OR”

```

Try it online!

## Explanation

```
V€Ḅ“n|ḃ’b⁹¤æ»ị“N“”ż“AND “OR X“OR”  Main Link
 €                                 For each character
V                                    evaluate it (into 0 or 1)
  Ḅ                                  convert the input string to binary
   “n|ḃ’b⁹¤                        [106, 86, 150]:
   “n|ḃ’                             6968982
        b                            in base
         ⁹                           256
           æ»                      Right shift each number by the input (those three numbers encode whether or not the N needs to be present)
              ị                      and index into
               “N“”                  ["N", ""] (odd = N, even = "", since Jelly lists wrap)
                   ż                 interleave it with
                    “AND “OR X“OR”   "AND ", "OR X", "OR"
                                    Final result is [N]AND [N]OR X[N]OR

```

# Answer
> 3 votes
# Python 3, ~~98~~ ~~88~~ 78 bytes

```
lambda s:'%sAND %sOR X%sOR'%(*[eval(s[0]+o+s[1]+'!='+s[2])*'N'for o in'&|^'],)

```

Try it online!

*Thanks to ovs for -20 bytes*

# Answer
> 2 votes
# Pyth, 53 bytes

```
%"%sAND %sOR X%sOR"[*\Nn&=vz1/z110*\Nn%z2>z2*\N%%z9 2

```

Try it online!

Port of a previous version of Stef's Python 3.8 answer.

# Pyth, ~~64~~ 61 bytes

-3 bytes by using string formatting.

```
A,shzs@z1=Tsez%"%sAND %sOR X%sOR"[?x&GHT\Nk?x|GHT\Nk?xxGHT\Nk

```

Try it online!

First time golfing in Pyth!

# Answer
> 2 votes
# Charcoal, 33 bytes

```
Ｎθ⭆vAND jOR XiOR⎇‹ι_ι×NΣ§◧⍘℅ι01⁸θ

```

Try it online! Link is to verbose version of code. Explanation: The lowercase letters' ASCII codes encode the binary patterns for where the `N`s appear. This algorithm actually depends on the input being an integer and the output being in upper case. Although the input is taken in base 10, the cyclic indexing means that the values are equivalent to base 2.

```
Ｎθ                                  Input the 3-digit number
   vAND jOR XiOR                    Literal string `vAND jOR XiOR`
  ⭆                                 Map over characters and join
                  ι                 Current character
                 ‹                  Is less than
                   _                Literal `_`
                ⎇                   If true then
                    ι               Current character else
                      N             Literal `N`
                     ×              Repeated by
                       Σ            Extract decimal value of
                            ι       Current character
                           ℅        ASCII code
                          ⍘  01     Converted to base 2
                         ◧     ⁸    Left padded to length 8
                        §           Cyclically indexed by
                                θ   Input number

```

# Answer
> 2 votes
# Python 3.8, 72 59 bytes

```
lambda n:f'{n%15%2*"N"}AND {n*3%17%2*"N"}OR X{n%9%2*"N"}OR'

```

Try it online!

Expects input as a decimal number.

*-13 bytes thanks to ovs' modular dark magic*

I squinted at the numbers very hard until I found these three formulae ovs chained all the modulos:

* `n&1!=n//110` \<=\> "the last digit is 1 and n is not 111; or n == 110"
* `n%2!=(n>2)` \<=\> "the last digit is 0 and n is nonzero; or n == 001"
* `n%9%2` \<=\> "the number of 1 in the digits of n is odd"

# Answer
> 1 votes
# 05AB1E, 35 bytes

```
’n€ƒxš¯š¯’4ôuεI`Š…*+~Nè.VQi'Nõ.;]ðý

```

Try it online or verify all test cases.

**Explanation:**

```
’n€ƒxš¯š¯’                 # Push dictionary string "nandxnornor"
  4ô                       # Split it into parts of size 4: ["nand","xnor","nor"]
    u                      # Uppercase each string: ["NAND","XNOR","NOR"]
     ε                     # Map over each string:
      I                    #  Push the input
       `                   #  Pop and push its digits separated to the stack
        Š                  #  Triple-swap the values on the stack: a,b,c → c,a,b
         …*+~              #  Push string "*+~"
             Nè            #  Index the map-index into this string
               .V          #  Execute it as 05AB1E code:
                           #   *: Multiply the top two values on the stack
                           #   +: Add the top two values on the stack
                           #   ~: Bitwise-OR the top two values on the stack
                 Qi        #  If this is equal to the third value that was on the stack:
                   'Nõ.;  '#   Remove the first "N" in the string
     ]                     # Close the if-statement and map
      ðý                   # And join the list with space delimiter
                           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `’n€ƒxš¯š¯’` is `"nandxnornor"`.
The `’n€ƒxš¯š¯’4ôu` could alternatively also have been `.•UNœTÇ¨₆~•#` for the same byte-count.

# Answer
> 1 votes
# C (gcc), <sup>~~78~~</sup> 73 bytes

Saved 5 bytes thanks to ceilingcat!!!

```
f(n){n=1<<n%6;printf("NAND %sOR X%sOR"+!(n&38),"N"+!(n&22),"N"+!(n&26));}

```

Try it online!

Inputs a three digit decimal number representing the two boolean arguments and the result of a boolean operator and outputs all possible operators to `stdout`.

Uses that super-handy lookup table from Arnauld's JavaScript answer.

# Answer
> 0 votes
# Java (OpenJDK 8), 143 bytes

```
void A(int a){for(int i=-1;i++<5;)if((7+21*((a+2)/4)>>i&1)==a%2)System.out.print(new String[]{"AND","OR","XOR","NAND","NOR","XNOR"}[5-i]+" ");}

```

Try it online! (More details inside)

Input is a single 3 digit number, interpreted as binary. Example input: "A(0b101);"

Explanation:

```
 (...)
 if((7+21*((a+2)/4)>>i&1)==a%2)
     7+21*(       )                 // The shortest interpolation equation (see bottom of tio.) I could find, for the "x" values of
                                    //   0, 1, 2, representing 00_, 01_ / 10_, 11_ respectively.
           (a+2)/4                  // The sum of the second and third bit, found this equation with brute force,
                                    //   alternative: (a|1)/3, needs parentheses because of bit operation order.
                   >>i&1            // The bit at i, delete all bits except the first to compare it with:
                        )==a%2)     // The first digit of a. (like "number % 10", except for binary)

```

And, I'm pretty sure you can print the answer when asked to return it.

---
Tags: code-golf, logic-gates
---


# Question
Title: Convert negadecimal to decimal (and back)
Negadecimal, also known as base -10, is a non-standard positional numeral system.

Take the number \\$1337\_{10}\\$. In decimal, this has the value one thousand three hundred thirty seven, and can be expanded to:

$$1\cdot10^3+3\cdot10^2+3\cdot10^1+7\cdot10^0$$

$$(1000)+(300)+(30)+(7)$$

In negadecimal, instead of \\$10^n\\$, each digit would be multiplied by \\$(-10)^n\\$:

$$1\cdot(-10)^3+3\cdot(-10)^2+3\cdot(-10)^1+7\cdot(-10)^0$$

$$(-1000)+(300)+(-30)+(7)$$

Thus, \\$1337\_{-10}\\$ is \\$-723\_{10}\\$ in decimal. (An interesting consequence of this is that negative signs are unnecessary in negadecimal; any integer can be represented as `/[0-9]+/`.)

In this challenge, your score is the sum of the lengths of two programs or functions:

* One to convert a number in negadecimal to decimal
* One to convert a number in decimal to negadecimal

All inputs will be integers. You must be able to handle negative numbers. You can take input and output in any reasonable way. This is code golf, so the shortest answer in bytes per language wins.

## Test cases

**Negadecimal to decimal:**

```
1337   -> -723
0      -> 0
30     -> -30
101    -> 101
12345  -> 8265

```

**Decimal to negadecimal:**

```
-723   -> 1337
0      -> 0
1      -> 1
21     -> 181
-300   -> 1700
1000   -> 19000
-38493 -> 179507

```

# Answer
> 8 votes
# 05AB1E, 6 bytes

## Nega to Deca

```
T(ö

```

Try it online!

## Deca to Nega

```
T(в

```

Try it online!

# Answer
> 8 votes
# JavaScript (ES6), 25 + 55 = 80 bytes

## Negadecimal to decimal (25 bytes)

```
f=n=>n&&n%10-10*f(n/10|0)

```

Try it online!

### How?

This one is pretty straightforward. We recursively compute:

$$f(n) = \cases{ 0, n=0\\ (n \bmod 10) - 10\times f\left(\left\lfloor\dfrac{n}{10}\right\rfloor\right), n\>0}$$

## Decimal to negadecimal (55 bytes)

```
f=(n,i=n%10,k=n>0?-n:~n-i+(i+=10))=>n?f(k/10|0)+i%10:''

```

Try it online!

### How?

In JS, the result of the `%` operator has the same sign as the dividend. For instance, `-17 % 10` is `-7` rather than `3` (like in Python), which is what we'd really like to get here. A possible workaround would be:

```
(n % 10 + 10) % 10

```

Besides, we also need to compute \\$\left\lfloor n/-10\right\rfloor\\$ with \\$n\\$ either positive or negative. This can be done with:

```
Math.floor(n / -10)

```

but this expression is a bit lengthy.

Rather than dealing with both issues separately, we explicitly test the sign of \\$n\\$ and compute the variables `i` and `k` accordingly:

* We unconditionally set `i = n % 10`.
* If \\$n\>0\\$, we define `k = -n` and leave `i` unchanged.
* If \\$n\le 0\\$, we define `k = ~n + 10` and add \\$10\\$ to `i`. Both operations are merged into `k = ~n - i + (i += 10)`.

We then can use `k / 10 | 0` and `i % 10` in both cases.

# Answer
> 8 votes
# JavaScript (Node.js), 59 bytes

```
f=(p,e=n=>n&&(i=(n%10+10)%10)-p*e((n-i)/p))=>e
f(10)
f(-10)

```

Try it online! `f` defines a helper function. `f(10)` returns a function that converts from negadecimal to decimal while `f(-10)` returns a function that converts from decimal to negadecimal.

# Answer
> 5 votes
# Jelly, 8 bytes

Negadecimal to decimal:

```
ḅ-10

```

Try it online!

Decimal to negadecimal

```
b-10

```

Try it online!

Input as an integer, output as a list of digits. +2 total bytes (+1 to each) to I/O as integers

# Answer
> 5 votes
# Wolfram Language (Mathematica), ~~17~~ 13+35 = 48 bytes

From negadecimal:

```
Fold[#2-10#&]

```

Try it online!

Input a list of digits.

To negadecimal:

```
f@0=0
f@a_:=f@-⌊a/10⌋||a~Mod~10

```

Try it online!

Return an `Or` of digits, including a leading zero.

+1 byte to output as an integer instead: Try it online!

# Answer
> 5 votes
# Lisp Flavored Erlang, 33 + 59 + 59 = ~~153~~ 151 bytes

```
(defun m(X Y)(rem(+(rem X Y)Y)Y))
(defun n(N)(if(== N 0)0(-(m N 10)(*(n(floor(/ N 10)))10))))
(defun d(N)(if(== N 0)0(+(m N 10)(*(d(ceil(/ N -10)))10))))

```

`n` computes the decimal, given a negadecimal. `d` computes the reverse.

Both functions take & return a regular integer.

Erlang's `rem` function works like JavaScript's instead of like Python's, which is why the `m` function is necessary. I save some total bytes by reusing it — if this were 2 separate challenges, it would be inlined as each function only uses it once.

Edit: Rearranged some of the function calls to save a couple bytes without changing logic

# Answer
> 4 votes
# Factor, 28 + 59 = 87 bytes

### Negadecimal to decimal

```
[ 0 [ swap 10 * - ] reduce ]

```

Try it online!

Takes an array of negadecimal digits and returns an integer.

```
[
  0 [ ... ] reduce   ! Reduce over the digits with starting value of 0...
    swap 10 * -      ! ( accum digit -- accum' ) Evaluate accum * -10 + digit
]

```

### Decimal to negadecimal

```
[ [ dup 0 = not ] [ -10 2dup / ceiling -rot rem ] produce ]

```

Try it online!

Takes an integer and returns an array of negadecimal digits in reverse order. Does not produce any leading zeros, which means the input of 0 gives an empty array.

```
[
  [ cond ] [ loop ] produce   ! Starting with the value of n, loop until cond gives false
                              ! and collect the top values during the loop
    dup 0 = not               !   Cond: stop if top is 0
                              !   Loop: yield the last digit and keep the higher value
    -10 2dup / ceiling        !   ( n -- n -10 keep ) keep = ceil(n/-10)
    -rot rem                  !   ( keep yield ) yield = n%-10 (non-negative mod)
]

```

# Answer
> 4 votes
# Husk, 8 bytes

## Negadecimal to decimal, 4 bytes

```
B_10

```

Try it online!

input as list of digits, output as integer.

## Decimal to Negadecimal, 4 bytes

```
B_10

```

Try it online!

input as integer, output as list of digits.

# Answer
> 4 votes
# Python 2, 31 + 34 = 65 bytes

## Negadecimal to decimal, ~~32~~ 31 bytes

Saved a byte thanks to xnor!!!

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

```

Try it online!

## Decimal to negadecimal, ~~42~~ ~~35~~ 34 bytes

Saved 7 bytes thanks to att!!!
Saved another byte thanks to xnor!!!

```
g=lambda n:n and n%10+10*g(0-n/10)

```

Try it online!

# Answer
> 4 votes
# K (oK), 40 bytes

## Negadecimal to decimal, 10 bytes

```
{y+x*-10}/

```

Try it online!

## Decimal to negadecimal, 30 bytes

-8 bytes thanks to coltim!

```
{$[~x;0;(10*o@-_-x%-10)+10!x]}

```

Try it online!

# Answer
> 3 votes
# Racket, 106 bytes

## Negadecimal to decimal, 39 bytes

```
(λ(x)(foldl(λ(a b)(+(* -10 b)a))0 x))

```

Try it online!

Takes an array of negadecimal digits and returns an integer.

## Decimal to negadecimal, 67 bytes

```
(define(d x)(if(= 0 x)0(+(modulo x 10)(*(d(ceiling(/ x -10)))10))))

```

Try it online!

Takes the input as an integer and returns an integer.

# Answer
> 3 votes
# Scala, 15 + 71 = 86 bytes

### Negadecimal to decimal

```
_.:\(0)(_-10*_)

```

Try them both online!

Takes input as a reversed list of digits.

This is rather straightforward - multiply the first digit by -10, add the second digit to that, multiply that by -10, and so on.

### Decimal to negadecimal

```
Seq.unfold(_){x=>val m=(x%10+10)%10;Option.when(x*x>0)(m->(m-x)/10)}:+0

```

Returns a reversed list of digits, with a leading zero (at the end).

This is not so trivial. Because of the way Scala's `%` works, we can't just use `x%10`, as it maintains the sign of `x` and not `10`. 10 has to be added to `x%10` to ensure it is positive, and then `%10` is done again.

# Answer
> 3 votes
# C (gcc), 28 + 43 = 71 bytes

## Negadecimal to decimal, 28 bytes

```
f(n){n=n?n%10-10*f(n/10):0;}

```

Try it online!

## Decimal to negadecimal, ~~48~~ ~~45~~ 43 bytes

Saved 3 bytes thanks to xnor!!!
Saved 2 bytes thanks to rtpax!!!

```
g(n){n=n?n%~9+10*(g(n/~9+(n=n%~9<0))+n):0;}

```

Try it online!

# Answer
> 3 votes
# Brachylog, 19 bytes

```
{×₁₀ʰ↔-}ˡ

```

Try it online!

```
≜{×₁₀ʰ↔-}ˡ

```

Try it online!

Negadecimal input and output is as digit lists. The decimal to negadecimal program uses reversed I/O and is also impressively slow, as it uses pure brute force (coming out 6 bytes shorter than a saner implementation).

```
{      }ˡ    Left fold over input negadecimal digits:
 ×           multiply
    ʰ        the accumulator
  ₁₀         by 10,
     ↔-      subtract it from the next digit.

≜             Try outputting all integers until the output
 {×₁₀ʰ↔-}ˡ    is the negadecimal representation of the input.

```

# Answer
> 3 votes
# , 71 bytes

*Combined negadec\_to\_dec and dec\_to\_negadec code thanks to user, and inspired by Neil's answer*

```
b=function(p)d=function(x)`if`(x,(y=x%%10)-p*d((x-y)/p),0)
b(10)
b(-10)

```

Try it online!

---

# , ~~49~~ ~~47~~ 41 + 47 = 88 bytes

*Separate functions*

**negadecimal to decimal (~~49~~ ~~47~~ 41 bytes):**

*Edit: -2 bytes (and, as a consequence, -6 more bytes) thanks to att*

```
d=function(x)`if`(x,x%%10-10*d(x%/%10),0)

```

Try it online!

**decimal to negadecimal (47 bytes):**

```
d=function(x)`if`(x,(y=x%%10)+10*d((y-x)/10),0)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 5 + 18 = 23 bytes

## Negadecimal to decimal:

```
Ｉ↨Ｓ±χ

```

Try it online! Link is to verbose version of code. This is just custom base conversion with a base of `-10`.

## Decimal to negadecimal:

```
ＮθＰ0Ｗθ«←Ｉ﹪θχ≔±÷θχθ

```

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

```
Ｎθ

```

Input the decimal number.

```
Ｐ0

```

Print a `0` in case the input is zero.

```
Ｗθ«

```

Repeat until the input is zero.

```
←Ｉ﹪θχ

```

Print the next digit in right-to-left order.

```
≔±÷θχθ

```

Divide the input by `10` and change its sign. (Sadly this is not the same thing as dividing the input by `-10`.

# Answer
> 2 votes
# Ruby 2.7, ~~69~~ ~~68~~ 66 bytes

---

# ~~24~~ 23 bytes

*-1 byte thanks to Bubbler*

```
->x{x.reduce{_2-_1*10}}

```

Try it online!

TIO uses an older version of Ruby, while in Ruby 2.7, we've numbered parameters, which saves 3 bytes.

---

# ~~45~~ 43 bytes

```
f=->x,s=''{x!=0?f[-~~(x/10),"#{x%10}"+s]:s}

```

Try it online!

---
Tags: code-golf, number, base-conversion
---


title: Descending digit sequences

text:
# Question
Title: Descending digit sequences
### Introduction

As an example, let's take the number `7`. We then duplicate this and place 7 spaces in between. We get this:

```
7_______7

```

After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:

```
7_______7
 6543210

```

Then, we just merge the two of them, so:

```
7_______7
 6543210  becomes

765432107

```

This will be out output for **N = 7**.

Looks easy, right? Now let's take **N = 12**. We again insert 12 spaces between the two numbers, which gives us:

```
12____________12

```

Then we start the decrement:

```
12____________12
  111098765432

```

And this finally gives us:

```
1211109876543212

```

**As you can see, the descending part ends at 2, *not* at 0**.

### Task

Given an integer, **greater than 1**, output the descending sequence as shown above.

### Test cases

```
Input   Output

2       2102
3       32103
4       432104
5       5432105
6       65432106
7       765432107
8       8765432108
9       98765432109
10      10987654321010
11      111098765432111
12      1211109876543212
13      13121110987654313
14      141312111098765414
15      1514131211109876515
20      201918171615141312111020
99      9998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150499
100     1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100

```

This is , so the submission with the fewest number of bytes wins!

# Answer
> 8 votes
# CJam, 11 10 bytes

```
q4*~,W%s<\

```

Try it online. Assumes there is a trailing newline in the input. (Thanks to @jimmy23013 for saving a byte.)

### Explanation

At the end of each line is what the stack looks like at that point (using `4` as an example).

```
q4*  e# Push input x 4 times, separated by newlines. ["4\n4\n4\n4\n"]
~    e# Evaluate, separating the 4's and converting them to numbers. [4 4 4 4]
,W%  e# Take the range of x and reverse it. [4 4 4 [3 2 1 0]]
s<   e# Cast to string and take the first x characters. [4 4 "3210"]
\    e# Swap the top two to get the final result. [4 "3210" 4]

```

# Answer
> 8 votes
# Julia, 30 bytes

```
n->"$n"join(n-1:-1:0)[1:n]"$n"

```

This is an anonymous function that accepts an integer and returns a string. To call it, assign it to a variable.

We construct and join the descending sequence from *n*-1 to 0, and take the first *n* characters from the resulting string. We prepend and append this with the input as a string.

Verify all test cases online

# Answer
> 5 votes
## JavaScript (ES6), ~~55~~ 52 bytes

```
n=>n+[...Array(m=n)].map(_=>--m).join``.slice(0,n)+n

```

Edit: Saved 3 bytes thanks to @WashingtonGuedes.

# Answer
> 5 votes
## Haskell, 44 bytes

```
s=show
f n=s n++take n(s=<<[n-1,n-2..])++s n

```

Usage example: `f 14` -\> `"141312111098765414"`.

# Answer
> 4 votes
# Python 2, ~~82~~ ~~72~~ ~~58~~ 53 bytes

```
lambda x:`x`+''.join(map(str,range(x)[::-1]))[:x]+`x`

```

Try it here!

Thanks to @Alex for teaching me that `repr(x)` = ``x`` saving me a bunch of bytes!

# Answer
> 3 votes
## Pyth, 11 bytes

```
++Q<jk_UQQQ

```

Two alternative versions, which are all also 11 bytes (*sigh*):

```
s[Q<jk_UQQQ
pQp<jk_UQQQ

```

```
  Q           the input
       UQ     [0, 1, ..., input-2, input-1]
      _       reverse
    jk        join on empty string
   <     Q    first (input) characters
          Q   the input again
++            concatenate everything so it prints on one line

```

Try it here.

# Answer
> 3 votes
# Jelly, 10 bytes

```
Ȯ’r0DFḣ³Ḍ³

```

Try it online!

### How it works

```
Ȯ’r0DFḣ³Ḍ³  Main link. Input: n

Ȯ           Print n.
 ’          Decrement to yield n - 1.
  r0        Create a range from n - 1 to 0.
    D       Convert each integer to base 10 (array of decimal digits).
     F      Flatten the resulting array.
      ḣ³    Keep the first n elements.
        Ḍ   Convert from base 10 to integer.
         ³  Print the integer and set the return value to n.
            (implicit) Print the return value.

```

# Answer
> 3 votes
# Japt, 13 bytes

```
U+Uo w ¬¯U +U

```

Test it online!

### How it works

```
               // Implicit: U = input integer
  Uo           // Create the range [0..U).
     w         // Reverse.
       ¬       // Join.
        ¯U     // Slice to the first U chars.
U+         +U  // Append U on either end.

```

# Answer
> 3 votes
# Retina, 98 110

Longest answer so far :-/

```
.+
$&;$&$*:
+`:(:+)$
$& $1
 (:)*
$#1
\d+$
$&0 $&0
T`d`,`\d+$
+`:(.*),
$1
+`. ,

(.+);(.*)
$1$2$1

```

Try it online.

# Answer
> 2 votes
# MATL, 15 bytes

```
VG:qPVXvG:)GVhh

```

*EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.*

**Try it online!**

```
V                 % input n. Convert to string
 G:               % range [1,2,...,n]
   qP             % convert into [n-1,n-2,...,0]
     VXv          % convert to string, no spaces
        G:)       % take first n characters only
           GV     % push input as a string, again
             hh   % concat horizontally twice

```

# Answer
> 2 votes
# Pure Bash, 49

```
eval printf -va %s {$[$1-1]..0}
echo $1${a::$1}$1

```

Or:

# Bash + coreutils, 48

```
echo $1$(seq $[$1-1] -1 0|tr -d \\n|head -c$1)$1

```

# Answer
> 2 votes
# Vitsy, 35 bytes

Since Vitsy isn't aware of how to make strings out of numbers, I implemented finding the length of the number in decimal places in the second line.

```
V0VVNHVv[XDN1mv$-DvD);]VN
1a/+aL_1+
```

Explanation:

```
V0VVNHVv[XDN1mv$-DvD);]VN
V                          Save the input as a global final variable.
 0V                        Push 0, push input.
   VN                      Output the input.
     H                     Push the range 0...intput.
      Vv                   Push the input, then save it as a temp variable.
        [             ]    Do the stuff in brackets infinitely or until exited.
         X                 Remove the top item of the stack.
          DN               Duplicate, then pop as output.
            1m             Calls the first line index, retrieving length.
              v            Pop the temp var and push it to the stack.
               $           Switch the top two items of the stack.
                -          Subtract them.
                 Dv        Duplicate, then pop one as a temp var.
                   D);     If it's zero, exit the loop.
                       VN  Output the global var.

1a/+aL_1+
1a/+       Add .1. This makes sure we don't throw errors on input 0.
    a      Push ten.
     L     Pop the top item as n, push the log base n of second to top.
      _    Make it an int.
       1+  Add 1.
```

Try it Online!

Verbose mode for lols:

```
save top as permanent variable;
push 0;
save top as permanent variable;
save top as permanent variable;
output top as number;
push all ints between second to top and top;
save top as permanent variable;
save top as temporary variable;
begin recursive area;
remove top;
duplicate top item;
output top as number;
push 1;
goto top method;
save top as temporary variable;
switch the top two items;
subtract top two;
duplicate top item;
save top as temporary variable;
duplicate top item;
if (int) top is not 0;
generic exit;
end recursive area;
save top as permanent variable;
output top as number;
:push 1;
push 10;
divide top two;
add top two;
push 10;
push ln(top);
replace top with int(top);
push 1;
add top two;
```

# Answer
> 2 votes
# Retina, 63 bytes

```
.+
$0,y$0$*y$0$*x
x
$'_
(x)*_
$#1
+`(y+)y(.)
$2$1
,(\d+).*
$1$`

```

There is still quite some room for golfing...

Try it online!

# Answer
> 1 votes
# Java, 93 bytes

```
String x(int v){String o=""+v;for(int i=v-1,c=o.length();o.length()-c<v;i--)o+=i;return o+v;}
```

# Answer
> 1 votes
## Ruby, 41 bytes

```
->n{[n]*2*(r=0...n).to_a.reverse.join[r]}

```

# Answer
> 1 votes
# Milky Way 1.6.5, ~~27~~ 25 bytes

```
I'::%{K£BCH=}<ΩHG<+<;+!

```

---

### Explanation

```
I                        ` empty the stack
 '::                     ` push 3 copies of the input
    %{K£BCH=}            ` dump digits of reversed range(n) as strings [n-1...0]
             <ΩHG<+<;+   ` select the first nth digits and pad them with n
                      !  ` output

```

---

### Usage

```
$ ./mw <path-to-code> -i <input-integer>

```

# Answer
> 1 votes
# Perl 6, 31 bytes

```
{$_~([R~] ^$_).substr(0,$_)~$_}

```

```
{
  $_ # input
  ~  # string concatenated with
  ([R~] ^$_)    # all numbers up to and excluding the input concatenated in reverse
  .substr(0,$_) # but use only up to the input number of characters
  ~
  $_
}

```

### Usage:

```
for 2,3,7,12,100 {
  say {$_~([R~] ^$_).substr(0,$_)~$_}( $_ )
}

```

```
2102
32103
765432107
1211109876543212
1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100

```

# Answer
> 1 votes
## Perl, 43 + 2 = 45 bytes

I'm happy that I didn't used `reverse` and neither `substr`:

```
"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_

```

Requires the `-pl` flags.

```
$ perl -ple'"@{[1-$_..0]}"=~s.\D..gr=~/.{$_}/;$_.=$&.$_' <<< 12
1211109876543212

```

How it works:

```
                                            # '-p' read first line into `$_` and
                                            # auto print at the end
"@{[1-$_..0]}"                              # Create a list from -1-n..0 and
                                            # join it on space. This becomes:
                                            #   "-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0"
              =~s.\D..gr                    # Remove all but digits:
                                            #   "11109876543210"
                        =~/.{$_}/;          # Match the n first characters from
                                            # the generated string
                                  $_.=$&.$_ # Append the match and the input

```

# Answer
> 1 votes
# C, ~~130~~ 125 bytes

```
#define p(x) printf("%i",x);
i,y,h;f(x){for(i=y=x;(i-=h)>=0;){p(y--)h=floor(log10(y))+1;}if(i+=h)p(h=floor(y/pow(10,i)))p(x)}

```

Ungolfed version (with explanation):

```
#define p(x) printf("%i",x);     // alias to print an integer
i,y,h;                           // helper variables
f(x){                            // function takes an integer x as arg
    for(i=y=x;(i-=h)>=0;){       // i -> the remaining space
                                 // y -> the current descending number
        p(y--)                   // print y (at first y==x)
        h=floor(log10(y))+1;     // h -> the number of digits in y-1
    }                            // do it until there is no more empty space
    if(i+=h)                     // if needs to chop the last number
        p(h=floor(y/pow(10,i)))  // chop and print (implicitly cast of double to int)
    p(x)                         // print x at the end
}                                // end function

```

The implicitly cast from double to int in `h=floor(...)` allowed the use of `#define p(x)` saving 5 bytes.

Test on ideone.

# Answer
> 1 votes
**R, 67 bytes (as function)**

```
# usage example : f(7)
f=function(i)cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')

```

**R, 63 bytes (input from STDIN)**

```
i=scan();cat(i,substr(paste((i-1):0,collapse=''),1,i),i,sep='')

```

# Answer
> 1 votes
## Brainfuck, 265 Bytes

This is only going to work with numbers \< 10

Try the golfed version here:

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

```

Ungolfed. Try it here:

```
>
,
---------- Convert to base 10
----------
----------
----------
--------

[->+>+<<]>>[-<<+>>]<

Fill up the grid
[
[->+>+<<]>>[-<<+>>] //duplicate number like [5][0] -> [5][5]
<-
]

<[<]> Go to cell 1
[

>[>] Scan for zero
> Move one more
+ Add one
<< Move two back
[<] Scan for zero
> Move one forward
- Subtract One
]

> Move one forward into actual numbers
[
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
]
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.

```

# Answer
> 1 votes
# PowerShell Core, 45 bytes

```
param($a)"$a$(($a-1)..0-join''|% su* 0 $a)$a"

```

Try it online!

## Explanation

```
($a-1)..0-join''|% su* 0 $a     # builds an array from a-1 to 0, joins them with no separators
                                  # and takes the `a` first chars

"$a ... $a"                       # surrounds the result with the parameter `a`

```

# Answer
> 0 votes
# Jelly, 11 bytes

```
ḶUDFṁ;D;@DḌ

```

Try it online!

There is also this kinda cheaty 9 byter, which only works due to how the `Y` command in the Footer works, so I'm not counting that.

Jelly's dislike of strings really hurts it here, and CJam's stack is just helpful enough to beat Jelly.

## How it works

```
ḶUDFṁ;D;@DḌ - Main link. Takes n on the left
Ḷ           - [0, 1, 2, ..., n-1]
 U          - [n-1, n-2, ..., 1, 0]
  D         - Convert each to digits
   F        - Flatten
    ṁ       - Take the first n
     ;D     - Append the digits of n
       ;@D  - Prepend the digits of n
          Ḍ - Convert from a list of digits to a number

```

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
Î<ŸRJ¹£¹.ø

```

Try it online!

```
Î<ŸRJ¹£¹.ø  # full program
        .ø  # surround...
      £     # first...
     ¹      # input...
      £     # chars of...
    J       # joined elements of...
  Ÿ         # [...
Î           # 0 ... input...
 <          # minus 1
  Ÿ         # ]...
   R        # reversed...
        .ø  # with...
     ¹      # input
            # implicit output

```

# Answer
> 0 votes
# Stax, <sup>~~9 8~~</sup> 7 bytes

```
îσQçφ╠♦

```

Run and debug it

-1 byte from recursive.

## Explanation (Unpacked)

```
rr$x%sy|S
r         range 0..n-1
 r        reversed
  $       converted to string
   x(     take n characters
     y    push n as string from register y
      |S  prepend and append it to the range
           implicit output

```

# Answer
> 0 votes
# Perl 5 `-p`, 40 bytes

```
print$_,("@{[1-$_..0]}"=~/\d/g)[0..$_-1]

```

Try it online!

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


# Question
Title: Does base n have any Rotate-Left-Double numbers?
## Task

A Rotate-Left-Double number in base \\$n\\$ is a number \\$m\\$, when its base-\\$n\\$ digits are rotated left once, equals \\$2m\\$. The base-\\$n\\$ representation of \\$m\\$ cannot have leading zeros.

One example in base 7 is the number 480, or \\$1254\_7\\$. When rotated left once, the value becomes \\$2541\_7 = 960\\$.

Given the base \\$n \ge 2\\$, determine if there exists a Rotate-Left-Double number in base \\$n\\$.

You can use your language's convention to represent truthy/falsy, or use two distinct values for truthy and falsy respectively.

## Scoring and winning criterion

Standard rules apply. Shortest code in bytes wins.

## Test cases

```
n -> answer (example if true)
-----------------------------
2 -> false
3 -> false
4 -> false
5 -> true (13 x 2 = 31)
6 -> false
7 -> true (1254 x 2 = 2541)
8 -> true (25 x 2 = 52)
9 -> true (125 x 2 = 251)
10 -> false
11 -> true [3,7]
12 -> true [2,4,9,7]
13 -> true [1,2,4,9,5,11,10,8,3,7]
14 -> true [4,9]
15 -> true [1,2,4,9,3,6,13,12,10,5,11,8]
16 -> true [2,4,9]
17 -> true [1,2,4,9]

```

Reference implementation in Python.

# Answer
# 05AB1E, ~~6~~ 5 bytes

```
ÍD<&Ā

```

-1 byte thanks to *@xnor* and *@Noodle9*.

Try it online or verify the first \\$\[2,100\]\\$ test cases.

**Explanation:**

```
Í       # Decrease the (implicit) input-integer by 2
        # Check that this input-2 is a power of 2 by:
 D      #  Duplicating it
  <     #  Decrease the copy by 1 (so integer-3)
   &    #  Take the bitwise-AND of input-2 and input-3
    Ā   #  Check that this is NOT 0
        # (after which the result is output implicitly)

```

***But wait, I don't see any use of bases nor rotation!***

When I saw the challenge in the Sandbox and was working on a solution, I noticed that the only falsey values in the first \\$n=\[2,500\]\\$ bases formed the sequence A056469: *number of elements in the continued fraction for \\$\sum\_{k=0}^n (\frac{1}{2})^{2^k}\\$*, which could be simplified to \\$a(n)=\left\lfloor2^{n-1}+2\right\rfloor\\$. Here a copy of the first 25 numbers in that sequence as reference:

```
2, 3, 4, 6, 10, 18, 34, 66, 130, 258, 514, 1026, 2050, 4098, 8194, 16386, 32770, 65538, 131074, 262146, 524290, 1048578, 2097154, 4194306, 8388610

```

It can also be note that all the numbers in this sequence are of the form \\$a(n)=2^n+2\\$, so checking whether \\$n-2\\$ is a power of \\$2\\$ will verify whether it's in this sequence. Since we want to do the invert here, and having a falsey result if it's in this sequence (or truthy if it's NOT in this sequence), we'll do just that, resulting in the code above.

**Mathematical proof that all falsey cases of the Left-Rotate-Double numbers are of the form \\$2^n+2\\$:**

Quote from @saulspatz at the Math SE, who provided me with this Mathematical proof to back up my theory I based on the first \\$n=\[2,500\]\\$ test cases. So all credit for this proof goes to him/her.

If \\$m\\$ is a \\$(d+1)\\$-digit Rotate-Left-Double number in base \\$n\\$, then $$m=xn^d+y\tag1$$ where \\$d\geq1,\ 0\<x\<n,\ 0\leq y\<n^d\\$. (Includes the rule that the number can't start with \\$0\\$.) Rotating \\$m\\$ gives \\$ny+x\\$, so we have \\$2xn^d+2y=ny+x\\$ or $$(n-2)y=(2n^d-1)x\tag2$$ If \\$n=2^k+2\\$ then \\$(2)\\$ gives \\$(n-2)|x\\$ (which means \\$x\\$ is divisible by \\$(n-2)\\$), since \\$2n^s-1\\$ is odd. But then \\$y\geq 2n^d-1\\$ which contradicts \\$y\<n^d\\$.

To show that these are the only falsey numbers, let \\$p\\$ be an odd prime dividing \\$n-2\\$. (Such a \\$p\\$ exists because \\$n-2\\$ is not a power of \\$2\\$.) In \\$(2)\\$ we can take \\$x=\frac{n-2}p\<n\\$ and we have to show that there exist an exponent \\$d\>0\\$ and \\$0\leq y\<n^d\\$ such that $$py = 2n^d-1$$ If we can find a \\$d\\$ such that \\$p|(2n^d-1)\\$, we are done, for we can take \\$y = \frac{2n^d-1}p\<n^d\\$.

By assumption, \\$n-2\equiv0\pmod{p}\\$ so \\$n\equiv 2\pmod p\\$. Therefore, $$2n^d\equiv1\iff 2\cdot2^d\equiv1 \iff 2^{d+1}\equiv 1\pmod p,$$ and by Fermat's little theorem, which states that \\$a^{p-1}\equiv 1\pmod p\\$, we can take \\$d=p-2\\$, because $$2^{p-2+1}\equiv 1 \iff 2^{p-1}\equiv 1 \pmod p$$

This completes the proof.
> 18 votes

# Answer
# Python 3, ~~19~~ 18 bytes

Uses Kevin Cruijssen's formula.

Returns `True`/`False`.

Saved a byte thanks to dingledooper!!!

```
lambda n:n-2&n-3>0

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, 21 bytes

```
.+
$*
^11(1(11)+)\1*$

```

Try it online! Link includes test cases. Explanation: The first stage converts to unary, while the last stage uses @KevinCruijssen's observation that a solution exists if `n-2` has a nontrivial odd factor.
> 2 votes

# Answer
# APL (Dyalog Extended), 9 bytes

```
⊃∧/⊤⎕-2 3

```

Try it online!

A full program that takes a single number \\$n\\$ from stdin, and prints 1 for true, 0 otherwise. APL doesn't have bitwise functions, so we need to explicitly convert to binary and apply boolean functions on each bit.

### How it works

```
⊃∧/⊤⎕-2 3  ⍝ Input: n (from stdin)
    ⎕-2 3  ⍝ [n-2, n-3]
   ⊤       ⍝ Convert to binary
           ⍝ (each number becomes a column in a matrix, aligned to bottom)
⊃∧/        ⍝ Check if the MSB of both numbers are 1,
           ⍝   i.e. the bit lengths of the two are the same

```
> 2 votes

# Answer
# C (gcc), 19 bytes

Uses Kevin Cruijssen's formula.

Returns \\$1\\$ for falsy and \\$0\\$ for truthy.

```
f(n){n=!(n-2&n-3);}

```

Try it online!
> 1 votes

# Answer
# Bash, ~~22~~ 20 bytes

Uses Kevin Cruijssen's formula.

Returns \\$1\\$ for falsy and \\$0\\$ for truthy.

Saved 2 bytes thanks to dingledooper!!!

```
echo $[!($1-2&$1-3)]

```

Try it online!
> 1 votes

# Answer
# Ruby, 14 bytes

Port of Kevin Cruijssen's answer, remember to upvote them!

```
->x{x-2&x-3>0}

```

Try it online!
> 1 votes

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

In JS 0 is falsy and everything else is truthy. Again, another port of Kevin Cruijssen's answer!

```
x=>x-2&x-3

```

Try it online!
> 1 votes

# Answer
# GolfScript, 5 bytes

In GolfScript 0 is falsy while any other value is truthy.

```
2-.(&

```

Try it online!
> 1 votes

# Answer
# Charcoal, 8 bytes

```
‹¹Σ⍘⊖⊖Ｎ²

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if RLD numbers exist otherwise no output. Explanation:

```
      Ｎ     Input as a number
    ⊖⊖      Decremented twice
   ⍘   ²    Converted to base 2
  Σ         Digital sum
‹¹          Is greater than 1

```

The only binary numbers with a digital sum of `1` or less are `0` and powers of `2`, so by @KevinCruijssen's proof a solution exists for all other values of `n`.
> 1 votes

# Answer
# Husk, 6 bytes

```
¬εΣḋ≠2

```

Try it online!

This one got simplified *really* quickly.
> 1 votes

# Answer
# Jelly, 5 bytes

```
_2&’$

```

Try it online!

Uses the fact that a given \\$n\\$ returns \\$0\\$ iff \\$n-2\\$ is a power of \\$2\\$, as pointed out by Kevin Cruijssen and the `n-2 & n-3` trick

## How they work

```
_2&’$ - Main link. Takes n on the left
_2    - n-2
    $ - To n-2:
   ’  -   Decrement; n-3
  &   -   n-2 & n-3

```
> 1 votes

---
Tags: code-golf, decision-problem, base-conversion
---