title: No co-prime neighbors

text:
# Question
Title: No co-prime neighbors
Given a list of positive integers, output whether every adjacent pair of integers in it shares a prime factor. In other words, output **truthy** if and only if **no** two neighboring integers in the list are co-prime.

In yet other terms: given a list of positive integers **\[a1 a2 … an\]**, output whether

**gcd(a1, a2) \> 1 && gcd(a2, a3) \> 1 && … && gcd(an−1, an) \> 1.**

The list will always contain at least two elements (n ≥ 2).

## However…

This challenge is also : the *codepoints* in your answer (whatever codepage it may be in) must satisfy the condition your program checks for.

For example, `print 2` is a valid program. As a list of Unicode codepoints it is **\[112 114 105 110 116 32 50\]**, which satisfies this condition: **112** and **114** share a factor of **2**; and **114** and **105** share a factor of **3**, etc.

However, `main` can *not* occur in a valid program (sorry!), as the Unicode codepoints of `m` and `a`, namely **109** and **97**, are coprime. (Thankfully, your submission needn’t be a full program!)

Your program isn’t allowed to contain codepoint 0.

## Test cases

Truthy:

```
[6 21] -> 1
[502 230 524 618 996] -> 1
[314 112 938 792 309] -> 1
[666 642 658 642 849 675 910 328 320] -> 1
[922 614 530 660 438 854 861 357 477] -> 1

```

Falsy:

```
[6 7] -> 0
[629 474 502 133 138] -> 0
[420 679 719 475 624] -> 0
[515 850 726 324 764 555 752 888 467] -> 0
[946 423 427 507 899 812 786 576 844] -> 0

```

This is : the shortest code in bytes wins.

# Answer
# MATL, 14 bytes

```
!TM1*Zdl2$Xdl-

```

This outputs a non-empty column vector of nonzero numbers as truthy, or a vector containing at least a zero entry as falsy.

### Explanation

```
!     % Implicit input. Transpose
TM    % Push input to latest function again
1*    % Multiply by 1 (does nothing, but matches factors)
Zd    % Compute gcd with broadcast: matrix of gcd of all pairs
l     % Push 1
2$    % The next function will use 2 inputs
Xd    % Extract diagonal 1 (i.e. that below the main diagonal) from the matrix
l-    % Subtract 1 from each entry. Implicitly display

```
> 15 votes

# Answer
# Haskell, ~~103~~ 100 bytes

EDIT:

* -3 bytes: Used a `d<-fz` guard to merge and shorten the last two lines.

`f` is the main function, which takes a list of integers and returns a `Bool`.

Note that the first two `ԁ`s (only) are Cyrillic (Komi) Unicode characters, and there's a tab character before the first one.

```
f	ԁ=zb[ԁ]id
zb[h:p:l]fz=z h p&&zb[p:l]fz
zb l fz=z 0 2
z 0z=z>z^0
z f fz|f<fz=z fz f|d<-fz=z d$f-d

```

Try it online! or test it on itself.

# How it works

* `f` is the main function. All it does is wrap its argument `ԁ` in a singleton list (because the prime ASCII value of `)` makes parentheses much more awkward to use than square brackets) and call `zb` with that and a dummy argument (the Haskell function `id` happens to have just the right characters to fit here).
    + Getting the same character to fit besides both of `=]` is impossible with plain ASCII, so the argument is named with the 2-byte Unicode character `CYRILLIC SMALL LETTER KOMI DE (ԁ)`, codepoint value `3*7*61=U+0501`, which fits with all of those and `[`.
        - Since the codepoint is not even (the smallest option that is a legal identifier and also even uses three bytes), this required using a tab character instead of a space before it.
        - A seven bytes longer plain ASCII option is to rename the argument: `f fz|bf<-fz=zb[bf]fz`.
* `zb` takes two arguments, a singleton list whose element is the real list of numbers being recursed on, and a dummy argument `fz` needed only to get a `z` before the function's `=`s.
    + When the inner list has at least two elements, the function `z` is called with the first two (named `h` and `p`), and if that returns `True`, `zb` recurses on the tail `p:l` of the list.
    + If the inner list has fewer than two elements, `zb` returns `True`. Since `=` needs to be followed by the character `z`, the simplest way to do this is to use a call of the `z` function that itself is known to return `True`.
* `z` takes two arguments and recursively calculates their greatest common divisor using subtraction (every other relevant integer division or gcd function is unavailable), returning `True` if it's greater than one.
    + The recursion ends when the first argument is `0`, with the second argument being the gcd. On this line the second argument is also named `z`. The character `1` is awkward here so `z^0` is used to get the number one.
    + Otherwise, if the first argument `f` is smaller than the second `fz`, they are swapped and `z` recurses.
    + Otherwise, the smaller argument is subtracted from the larger, then `z` recurses (also swapping the arguments, although that's just to avoid parentheses.)
> 14 votes

# Answer
# Husk, 8 bytes

For Truthy inputs it returns a positive integer, for Falsy it returns 0

```
←▼`Ṡt(ż⌋

```

Try it online! and Tested on its own codepoints

Uses Husk's codepage

```
Source -- [ ←  , ▼  , `  , Ṡ  , t  , (  , ż  , ⌋  ]
Hex    -- [0x06,0xbd,0x60,0xd0,0x74,0x28,0xeb,0x8d]
Dec    -- [6   ,189 ,96  ,208 ,116 ,40  ,235 ,141]

```

### Explanation

```
          -- implicit input, e.g                                  [63,36,18,3]
  `       -- flip the args of the next function
   Ṡ      -- some combinator (Ṡ f g x = f (g x) x)
    t     -- tail                                                 [36,18,3]
      ż   -- zipWith (note, keeps trailing elems of longer list)  [(63,36),(36,18),(18,3),(3)]
       ⌋  -- gcd                                                  [9,9,3,3]
     (    -- used just to match restricted source criteria
 ▼        -- minimum of the list                                    3
←         -- minus 1                                                2

```
> 10 votes

# Answer
# 05AB1E, 8 bytes

### Code

```
ü‚ÒüÃP≠P

```

Uses the **05AB1E** encoding, which gives us the following list of code points:

```
hex: [0xFC, 0x82, 0xD2, 0xFC, 0xC3, 0x50, 0x16, 0x50]
dec: [252,  130,  210,  252,  195,  80,   22,   80]

```

Try it online! or Verify the source code!

### Explanation

Since the gcd operator (`¿`) has a prime code point I had to look for other ways to check coprimality:

```
ü‚          # Get an array of adjacent pairs of the input
  Ò         # Factorize both elements of each pair in the array
   üÃ       # For each pair, get the intersection of both prime factorization lists
     P      # Product of each intersection (this leaves 1 when there is no intersection)
      ≠     # Check for each element whether it does not equal 1
       P    # Product of the booleans

```
> 10 votes

# Answer
# Japt, ~~8~~ 7 bytes

```
äj d¹¥Z

```

Test it online!

Code points:

```
Char    ä   j       d   ¹   ¥   Z
Hex    e4  6a  20  64  b9  a5  5a
Dec   228 106  32 100 185 165  90

```

### Explanation

```
 äj d¹ ¥ Z
Uäj d) ==Z
             Implicit: U = input array, Z = 0
Uä           For each pair of items in the array:
  j            Return whether the two items are coprime.
    d)       Return true if any items are truthy, false otherwise.
       ==Z   Return whether this is equal to 0 (false -> true, true -> false).
             Implicit: output result of last expression

```
> 5 votes

# Answer
# Jelly, ~~11~~ 9 bytes

```
,Pnælð2\P

```

Saved 2 bytes thanks to @Jonathan Allan.

Try it online!

Jelly has its own code-page and the codepoints of each character are

```
Chr Hex Dec
,   2c   44
P   50   80
n   6e  110
æ   16   22
l   6c  108
ð   18   24
2   32   50
\   5c   92
P   50   80

```

This tests for non-coprime numbers by checking if `lcm(a, b) != a*b`. There might be a shorter solution as I just filtered for characters with even codepoints.

## Explanation

```
,Pnælð2\P  Input: array A
      2\   For each overlapping sublist of size 2
     ð       Reduce it using this dyad
,              Pair
 P             Product
  n            Not equals, 1 if true else 0
   æl          LCM
        P  Product

```
> 5 votes

# Answer
# TI-BASIC, 38 bytes

```
Input L1:ΔList(cumSum(L1:augment(Ans+V,V+{0:2>sum(AnsL1=lcm(Ans+V,V+L1

```

TI-BASIC is tokenized into one- or two-byte tokens, as listed here.

The trickiest parts of this solution were:

1. The comma token is a prime number (43), forcing me to surround it with multiples of 43 (in this case the V token, which is 86).
2. The gcd( token is a large prime number (47881), which means it couldn't be used at all.

The tokens for this program come out to:

```
token     hex     dec
Input     0xDC    220
L1        0x5D00  23808
:         0x3E    62
ΔList(    0xBB2C  47916
cumSum(   0xBB29  47913
L1        0x5D00  23808
:         0x3E    62
augment(  0x14    20
Ans       0x72    114
+         0x70    112
V         0x56    86
,         0x2B    43
V         0x56    86
+         0x70    112
{         0x08    8
0         0x30    48
:         0x3E    62
2         0x32    50
>         0x6C    106
sum(      0xB6    182
Ans       0x72    114
L1        0x5D00  23808
=         0x6A    106
lcm(      0xBB08  47880
Ans       0x72    114
+         0x70    112
V         0x56    86
,         0x2B    43
V         0x56    86
+         0x70    112
L1        0x5D00  23808

```

# Explanation

```
Input L1:                   Prompt the user to input L1.

ΔList(cumSum(L1:            Take the differences of the prefix sum of L1,
                            which in effect removes the first element (result in Ans).

augment(Ans+V,V+{0:         Append a 0 to the end of Ans.
                            V defaults to 0, so adding it is a no-op.
                            Ans now holds L1 shifted to the left by one element,
                            with a 0 shifted in.

      AnsL1=lcm(Ans+V,V+L1  Take the least common multiple of each corresponding element
                            of Ans and L1, and check if each is equal to their product.
                            This returns a list of booleans, each 1 corresponding to
                            a co-prime pair. The last element (having been paired with 0)
                            will always be 1.

2>sum(                      Returns 1 if there is at most one 1 in the list, else 0.
                            Since the last element is always 1, this means
                            we return 1 only if there are no co-prime pairs.

```
> 5 votes

# Answer
# Pyth, 15 bytes

```
&F.bPiFNP.TtBQQ

```

**Try it here** or **Check out Test Suite.**

This is a collaborative effort between Erik the Outgolfer and Mr. Xcoder. Returns an inconsistent value (non-empty list) for truthy, and the empty list for falsy.

---

## ASCII-values

```
[38, 70, 46, 98, 80, 105, 70, 78, 80, 46, 84, 116, 66, 81, 81]

```

Which share the following factors:

```
[2, 2, 2, 2, 5, 35, 2, 2, 2, 2, 4, 2, 3, 81]

```

---

# Explanation

```
&F.bPiFNP.TtBQQ
           tBQ   Return [Q, Q[1:]] (Q = eval first line of input)
         .T      Transpose ^ without cropping absences
        P        Remove last element of ^
  .b          Q  Map in parallel on ^ (N) and Q (Y, ignored)
     iFN           GCD of N
    P              Prime factors of ^ (P(1) = [])
&F               Left fold (reduce) the result of the map with Logical AND (short-circuiting)

```

---

Without the requirement, this would've been a ~~7~~ 5-byte version accomplishing the same task (-2 thanks to FryAmTheEggman):

```
-1iVt

```

---

# Explanation

```
-1iVtQQ  Implicit QQ at the end
    tQ   Return Q[1:]
  iV  Q  Vectorized GCD on ^ and Q
-1       Remove every element of ^ from [1] (implicit singleton)

```
> 3 votes

# Answer
# Vyxal 3 `g`, 5 bytes

```
ϩĠ∑ȧv

```

Try it Online!

I could save a byte with codepoint zero... Outputs 0 if falsy, any other number is truthy in vyxal
> 1 votes

---
Tags: code-golf, array, restricted-source, decision-problem, primes
---


title: Output / Convert to unary number

text:
# Question
Title: Output / Convert to unary number
Your task is it to output a number as a unary string. You get the number of a non-negative integer input in the range of 0 - 2'000'000'000.

Rules

* You can choose any character for the digit you like. But it has to be the same everywhere and for every input.
* Output a unary string by outputting this character N times. N is the input.
* Input range is 0 - 2'000'000'000 (inclusive)
* A input of 0 result in a empty string except the optional starting and ending characters.
* You may or may not add optional starting and ending characters at the start and/or end, for example a newline character or `[` and `]`. If you do, all outputs (including of the input 0) must have one. This characters are different from the the character for the digit you have chosen.
* Input integer is given as decimal, hexadecimal, octal or binary number, whatever is convenient for you.
* You are free to use a pattern of multiple characters for a single digit. But it has to be the same pattern for all digits and for every input.
* Digit grouping is optional. If you use it, the group size has to be constant and the separation character has to be the same everywhere.
* Your program should finish in less than 4h on a modern desktop CPU with 4 GB of free RAM, for any valid input.
* Output is a string or stream of characters.

Examples / test cases:

```
Input  ->  Output

./yourProgram 1  -> 1
./yourProgram 12 -> 111111111111
./yourProgram 0  ->
./yourProgram 2000000000 | tr -d -c '1' | wc -c -> 2000000000
./yourProgram 32 -> 11111111111111111111111111111111

```

Non-golf example program:

```
#!/usr/bin/env python3
import sys

for i in range( int(sys.argv[1]) ):
  print("1", end='')

```

This is `code-golf`, so the shortest code wins.

Related but they have significant differences:

# Answer
# Python 3, 11 bytes

```
'0'.__mul__

```

Try it online!

Note: `0` could be any other character. Function returning a string.

# Python 3, 21 bytes

```
def f(n):print('0'*n)

```

Try it online!

Function which prints the string.
> 11 votes

# Answer
# TypeScript’s Type System, 62 bytes

```
type U<N,L extends 1[]=[]>=L extends{length:N}?L:U<N,[...L,1]>

```

Try it at the TypeScript Playground!

Type definition taking a generic integer type and recursively appending 1 to a tuple type until its length is the integer type.
> 7 votes

# Answer
# Charcoal, 1 byte

Try it online! Link is to verbose version of code. Explanation: Charcoal prints a number as a number of `-`, `|`, `/` or `\` symbols depending on the direction of the pivot, the default being horizontal.
> 7 votes

# Answer
# Raku, 4 bytes

```
1 x*

```

Try it online!
> 6 votes

# Answer
# Rust, 12 bytes

```
|a|vec![0;a]

```

Attempt This Online!
> 6 votes

# Answer
# Thunno 2, 1 byte

Try it online!

Uses a space as the character.

# Vyxal, 1 byte

```
I

```

Try it Online!

Same as above.
> 4 votes

# Answer
# C (gcc) `-O3`, 24 bytes

*-1 byte thanks to @12431234123412341234123*

```
f(n){n&&puts(f)+f(n-1);}

```

Try it online!

---

# C (gcc), 42 bytes

*Full program, input from stdin*

```
main(n){printf("%.*d",n,!scanf("%d",&n));}

```

Try it online!

---

# C (gcc) `-m32`, 44 bytes

*Full program, input as command line argument*

```
*p;main(n,v){printf("%.*d",atoi(1[p=v]),0);}

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 5 bytes

```
.+
$*

```

Try it online! Explanation: Outputs `1` repeated by the input count, with a trailing newline.

For Retina 1, remove the `$`, and then the program outputs `_` repeated by the input count, without a trailing newline.
> 4 votes

# Answer
# Lua, 21 bytes

```
print(('0'):rep(...))

```

Try it online!
> 4 votes

# Answer
# , 4 bytes

```
#&LF

```

Uses linefeed as the character. The large test case will not work on ATO, but `100 timex '# f 2000000000'` yields an average of 0.421414 seconds.

Attempt This Online!

```
#&LF
#     NB. copy
 &LF  NB. bond LF as the right argument

```
> 4 votes

# Answer
# Hexagony, ~~14~~ 12 bytes

```
(}?@_.)<!>*'

```

Try it online!

Layed out

```
   ( } ?
  @ _ . )
 < ! > * '
  . . . .
   . . .

```

### Explanation

`(}?` some irrelevant operations initially, then get the input

`<` branch, if 0 go to `@` and terminate, otherwise point the IP southeast

`(_` decrement the input cell and redirect the IP northeast

`}*)!` move the MP to the cell to the right, set that cell to 1 and print that out

`_>` redirect the IP back east

`*'` irrelevant operation, then move the MP back to the input cell

this then loops back to the branch command
> 4 votes

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

`x=>new String('a',x);`

Try it online!

My first time writing an answer here!
> 4 votes

# Answer
# \>\<\> (Fish), 10 bytes

```

```

Hover over any symbol to see what it does

Try it
> 3 votes

# Answer
# JavaScript, 15 bytes

```
n=>"".padEnd(n)

```

Try it online!

Returns the string. Uses a space as the character.

This might not be allowed, but for **9 bytes**

```
"".padEnd

```

Try it online!

*-1 from both thanks to @Arnauld*

# JavaScript, 22 bytes

```
n=>print("".padEnd(n))

```

Try it online!

Prints the string.
> 3 votes

# Answer
# Java (JDK), 11 bytes

```
"1"::repeat

```

Try it online!
> 3 votes

# Answer
# Arturo, 15 bytes

```
$=>[repeat"1"&]

```

Try it!
> 3 votes

# Answer
# jq, 8 bytes

```
"1"*.+""

```

Try it online!
> 3 votes

# Answer
## Pascal, 96 characters

```
program u(input,output);var i:integer;begin read(i);while i>0 do begin write('');i≔i−1 end end.

```

Necessary implementation characteristics: The value of `maxInt` must be ≥ 2000000000.
> 3 votes

# Answer
# Alice, 15 bytes

```
/ M \1*.n$@9ot

```

Try it online!

The new line at the end of the code is required
Uses tab as the output character

```
/ M \1*.n$@9ot    # Full program
/ M \1*           # Reads one argument as a string and multiply it by 1, this is our loop counter
       .n$@       # Stop if the counter is down to 0
           9o     # Output a <tab>
             t    # Decrement the counter
                  # Goes back to the beginning of the line

```
> 3 votes

# Answer
# Haskell, ~~18~~ 16 bytes

*-2 bytes thanks to Bubbler*

```
(`replicate`'a')

```

Attempt This Online!

On my machine, it finished in 48.68 seconds and had a max RSS of 4656 kb, well under the time and memory limits.
> 3 votes

# Answer
# 05AB1E, 2 bytes

Uses character `1`.

Try it online.

```
Î×

```

Uses character `0`.

Try it online.

```
°¦

```

Uses character `0` as well.

Try it online.

```
õú

```

Uses a space as character.

Try it online.

If different multiple output-characters would have been allowed, it could be 1 byte with:

Try it online.

**Explanation:**

```
$   # Push 1 and the input-integer
 ×  # Repeat the 1 the input amount of times as string
    # (which is output implicitly as result)

Î   # Push 0 and the input-integer
 ×  # Repeat the 0 the input amount of times as string
    # (which is output implicitly as result)

°   # Push 10 to the power of the (implicit) input-integer
 ¦  # Remove the leading 1 so only the 0s remain
    # (which is output implicitly as result)

õ   # Push an empty string ""
 ú  # Pad it with the (implicit) input-integer amount of leading spaces
    # (which is output implicitly as result)

∍   # Extend/shorten the (implicit) input to a length of the (implicit) input-integer
    # (which is output implicitly as result)

```
> 3 votes

# Answer
## Bash, 13 bytes (with calling other programs)

```
yes|head -n$1

```

##### Explanation

`yes` prints lines with the content `yes`. `head -n` will filter for the first n lines, n is given with `$1`. The line with `yes` is used as digit.

## Pure Bash, 29 ~~34~~ bytes

```
for((i=$1;0<i;i--));do [;done

```

##### Explanation

The `for((i=$1;0<i;i--))` will do the commands between `do` and `done` `$1` times. `[` is a builtin bash command that expects a test and a `]`, which isn't provided, so it prints a error message every time. The error message is used as digit.

I tried also this one:

```
$1||pwd;$1||0 $(($1-1))

```

Which works almost when the script is named 0 and in the current `$PATH`. But it fails with large inputs, so not a working solution.

##### Explanation

The `||` means, if that on the left side fails, try that on the right side instead (till the end of the line or `;`). If it doesn't fail ignore the part on the right side. If there is nothing on the left side, the right is also ignored.

This tries to call program `$1`, i.e. the first parameter provided. Since the script is named `0`, it will work with the input `0`. so it calls itself without any argument. And then, when it runs without an argument, `$1` will expands to nothing, which means do nothing and ignore the part right of `||`.

If the parameter `$1` is a `number>0`, it will fail to execute a program because there is no program with that name. This means a error message is printed to `stderr`, which we ignore, and then the right side of `||` is executed.

The `$1||pwd;` part means: If program `$1` is not valid, i.e. `$1` is a number above `0`, it calls `pwd`. `pwd` outputs something to `stdout` and it shouldn't change. So we can use it as a non-changing digit. The `$1||0 $(($1-1))` part means: If program `$1` is not valid, call `0` / itself with the parameter `$(($1-1))`. `$(($1-1))` means 1 subtracted from `$1`.

It fails with large input because it recursively calls itself and so a new process starts. But i can't create 2'000'000'000 processes on my PC.
> 3 votes

# Answer
# x86 / x86-64 machine-code, 7 bytes, as fast as memset

Just a function, not a full program, so we only need to `memset(buf, '1', n)` \+ append a terminating 0 to make an implicit-length C-style string in the buffer the caller supplies, of size `n+1` or larger.

This could be called from C in the x86-64 System V calling convention as `void to_unary(char *dst, int dummy, int dummy, size_t n)`. Size is limited only by address-space limits.

```
machine code | NASM source

              ; RDI or ES:EDI = output buffer of size n
              ; RCX or ECX = n
              to_unary:
 B031           mov al, '1'
 F3AA           rep stosb
 880F           mov byte [rdi], cl    ; RCX was zeroed by rep stos
 C3             ret

```

`stos` stores and *then* increments, so it leaves RDI pointing after the last byte it stored. We depend on the calling convention for DF=0 (increment not decrement), as is normal for all mainstream 32 and 64-bit calling conventions.

The same machine code bytes will do the same thing in 32-bit mode.

At first I was going to use `dec eax` / `stosb` for the terminator, with `1` instead of `'1'` as the unary digit "character". This would be 2 bytes in 32-bit mode only. But then I realized a `mov` store wouldn't need a displacement in the addressing mode, and that we had `cl`=0.

---

For an explicit-length-string version using separate pointer+length, we could return the input length after filling the input buffer (also leaving a pointer to the end in RDI). This would take the same total machine-code size: `push rcx` to start, `pop rax` at the end, instead of `mov [rdi], cl`.

---

**If the buffer is large and aligned, speed on typical modern CPUs, especially with the ERMSB feature, is basically as fast as typical libc memset, at least on Intel maybe not AMD.**

On a typical desktop, single-core memory bandwidth is usually close to maxing out the memory controllers. (Much lower per-core bandwidth on many-core Xeons.) Slower with page faults on the first access to newly allocated RAM, but this runs about as fast as it's possible for a single thread to go (for large aligned buffers), except by playing virtual memory tricks to map a range of virtual pages to the same memsetted page of '1's. With a misaligned buffer it's still probably under a second to fill 2GB. For small `n`, microcode startup overhead dominates, even on CPUs with the "fast-short-rep" feature. AMD CPUs may have slower `rep stos`, but even storing 1 byte per clock cycle would be way faster than the 4 hour requirement needs.
> 3 votes

# Answer
# jot(1), 10 bytes

```
jot -b1 $1

```

Try it online!

Outputs a stream of `1`s separated by newlines. TIO times out doing the 2 billion case, but it takes just 4 minutes on my Intel Mac

```
$ time jot -b 1 2000000000|wc -l
 2000000000
jot -b 1 2000000000  243.40s user 0.52s system 99% cpu 4:04.24 total
wc -l  2.61s user 1.70s system 1% cpu 4:04.24 total

```
> 3 votes

# Answer
# Befunge-93, 9 ~~15~~ ~~17~~ bytes

```
<,7_@#:+&

```

Try it online!

This program is pretty simple. It gets a number as input, then it decrements it by adding `-1`. `-1` is the value returned when there is no input left, so I'm able to just use one `&` symbol to get the numbers I need and just continue adding the current value and `-1` to decrement. Each time the number is decremented, the program checks if it is `0`, and if it is, it quits. I did this by using a bridge (`#`) to skip over the stop command (`@`) and the go backward to the `@` if the value is `0` using a horizontal if `_`. Previous versions of my program weren't linear, but rather 2d, so the control was taking up a lot of space. The bridge command allowed me to keep control linear. The program starts with a `<` to make the program go backwards, this is because the horizontal if statement `_` goes right if `0`, but I need it to go left, so I reversed the whole program because that's easier than reversing it's input.
> 2 votes

# Answer
# C (gcc), 49 bytes

*Full program, takes 1 argument*

```
main(a,v)int**v;{for(a=atoi(v[1]);a--;puts(*v));}

```

Try it online!
> 2 votes

# Answer
# Swift, 31 bytes

```
{.init(repeating:"1",count:$0)}

```

Try it online! A bit more verbose than some, but hopefully clear enough.
> 2 votes

# Answer
# Ruby, 9 bytes

```
->n{?1*n}

```

Attempt This Online!
> 2 votes

# Answer
**As a whole program:**

# F# (.NET Core), 66 bytes

```
[<EntryPoint>]let m a=[for _ in 1..(int(Seq.head a))->printf"1"];0

```

Try it online!

---

**As a function:**

# F# (.NET Core), 33 bytes

```
fun a->[for _ in 1..a->printf"1"]

```

Try it online!
> 2 votes

# Answer
# \[Matlab\], 9 bytes

```
ones(1,n)

```

ones generates mxn matrixes of 1s

---

# \[Matlab\], 16 bytes

second version upon remarks in the comments

```
s=@(n) ones(1,n)

```

anonymous function that generates mxn matrixes of 1s
> 2 votes

# Answer
## Batch, 26 bytes

```
@for/l %i in (1,1,%1)do cd

```

The `@` is needed to prevent unwanted echo of the `for` command, but echo of the `cd` command is per-iteration anyway so no `@` is needed. The four spaces are needed so that the code will parse correctly.
> 2 votes

# Answer
# simply, 17 bytes

This creates an anonymous anonymous function that returns the expected result:

```
fn($x)=>&tb($x,1)

```

This is a full program that does the same thing, but outputs it (also 17 bytes):

```
out&tb($argv[0]1)

```

---

## How does it work?

This runs the function `&tb`, which is an alias to `&tobase`.

It takes the number and the base.
It relies on JavaScript's `Number.prototype.toString(radix)` with a special case to handle unary (where it just outputs 1s).

---

## Ungolfed

Ungolfing both versions at the same time.

All examples here are executable on their own, and take a JSON array as input, with the value you wish.
This isn't a limitation of the program at all - it's just how you pass values to the compiler to populate the `$argv` variable.

All examples will be written with `&tobase` for clarity.

### Code-like

```
// Anonymous function - assigned to $fn
$fn = fn($x) => &tobase($x, 1);
// Calls the function and outputs the result
echo call $fn(argv[0], 1);

// Full program
echo &tobase($argv[0], 1);

```

### Plain-English-like

```
// Anonymous function - assigned to $fn
Set the variable $fn to an anonymous function with argument $x
Begin.
    Return the result of calling the function &tobase with the arguments $x, 1.
End.

// Calls the function and outputs the result
Display the result of calling the variable $fn with the arguments $argv[0], 1.

// Full program
Display the result of calling the function &tobase with the arguments $argv[0], 1.

```
> 2 votes

# Answer
# , 43 bytes

```
(int x){import std;return"1".replicate(x);}

```

not sure if I can make it much shorter. I can't just do a short lambda (`x=>...`) because it requires `replicate` from `std.array`. I tried doing some stuff with `iota` and `map` but that resulted in 4 bytes longer than this simpler solution.
> 2 votes

# Answer
# ForWhile (C version), 6 bytes

`{[9#)}`

prints n tabs

Running the program with input `2000000000` takes a bit over 2 minutes and consumes about 150kBit of memory (when using the debug build of the interpreter) so the program is well withing the time and memory limits.

Interpreter

online interpreter Note that the online interpreter does not satisfy the efficiency requirements

# Explanation

```
{    } anonymous procedure
 [  )  repeat n times
  9#   print tab

```

calling the procedure

```
{[9#)} 1$  store procedure at address 1
2000000000 1@? call procedure with argument `2000000000`

```

---

# ForWhile, 26 bytes

`99[_48-:0<!:[.'2*+1]).[9#)`

Full program, reads binary integer from standard input

```
99[                 )       \ repeat up to 99 times
   _                        \ get a byte from standard input
    48-                     \ subtract char-code of 0
       :0<!:[      ]        \ if value is non-negative
             .    1         \ temporarily remove condition from stack
              '2*+          \ duplicate current value and add new bit
                    ).      \ break loop if last character was less than 48
                      [9#)  \ print tab n times

```
> 2 votes

# Answer
# Piet \+ ascii-piet, 22 bytes (2×11=22 codels)

```
tabrjcdskcK  a?kqak kk

```

Try Piet online!

---

Explanation:

Prints `1` a total of `n` times.
> 2 votes

# Answer
# Python 3, 63 bytes

```
import sys

n = int(sys.argv[1])
output = '1' * n
print(output)

```
> 1 votes

# Answer
# Thue, 21 Bytes

```
0::=x
1::=x*
*x::=x**

```

Input is on the state and in binary, output is some number of xs (can be ignored) and the output number of asterisks on the state at the end.

Is this allowed?
> 1 votes

# Answer
# Swift, 33 bytes

```
let u={for _ in 1...$0{print(0)}}

```

The "grouping separator" here is a newline after every digit.
> 1 votes

# Answer
# Dyalog APL, 3 bytes

```
⍴∘0

```

This reshapes `0` to have the same length as the argument to the function, effectively repeating it input times.

For the same length, there's also `/∘0` and `⌿∘0`.
> 1 votes

# Answer
# Perl 5 (`-p`), 7 bytes

```
$_=1x$_

```

Try it online!
> 0 votes

# Answer
# PowerShell, 6 bytes

```
'1'*$n

```

Try it online!
> 0 votes

# Answer
# Scala 3, 5 bytes

```
"1"*_

```

Attempt This Online!
> 0 votes

---
Tags: code-golf
---


title: Numbers that are actually letters

text:
# Question
Title: Numbers that are actually letters
Given a non-negative integer input, write a program that converts the number to hexadecimal and returns a truthy value if the hexadecimal form of the number contains only the characters `A` through `F` and a falsey value otherwise.

---

Test cases

```
10
==> True (A in hexadecimal)

100
==> False (64 in hexadecimal)

161
==> False (A1 in hexadecimal)

11259375
==> True (ABCDEF in hexadecimal)

0
==> False (0 in hexadecimal)

```

---

Bonus: **-40 bytes** if your program prints `Only letters` for the challenge described above, `Only numbers` if the hexadecimal version of the number only contains the digits `0-9` and `Mix` if the hexadecimal number contains at least one number and at least one letter.

---

This is code golf. Standard rules apply. Shortest code in bytes wins. Either functions or full programs are allowed.

# Answer
# Pyth, 43 - 40 = 3 bytes

```
?&K@J.HQG-JG"Mix"%"Only %sers"?K"lett""numb

```

Test suite

This achieves the bonus. `Only numbers` and `Only letters` fortunately only differ by 4 letters. printf-style formatting is used with `%`.

The selection system is done by both taking the intersection of the hex with `G`, the alphabet, and subtracting out `G`. If neither ends up falsy, it's a mix, while if the intersection is falsy, it's numbers, and if the subtraction is falsy, it's letters.
> 23 votes

# Answer
# Pyth, 6 bytes

```
!-.HQG

  .HQ   # Converts the input to hexadecimal
 -   G  # Deletes all letters
!       # If empty, output True, else False

```

Test it here
> 16 votes

# Answer
# Jelly, 6 bytes

```
b16>9P

```

Try it online!

### How it works

```
b16>9P  Input: z

b16     Convert the input to base 16.
   >9   Compare each resulting digit with 9; return 1 iff greater.
     P  Take the product of the resulting Booleans.

```
> 12 votes

# Answer
## Python, 24 bytes

```
lambda n:min('%x'%n)>'9'

```

Converts the input a hex string (without `0x` prefix) with `'%x'%n`. Sees if all its chars are greater than `'9'` (which letters are) by seeing if the `min` is above `'9'`.
> 12 votes

# Answer
# TeaScript, 11 bytes ~~13 15 16~~

```
xT(16)O(Sz)

```

Pretty simple. This uses TeaScript 2.0. You can get this version from the Github

## Explanation

```
        // Implicit: x = input, Sz = alphabet
xT(16)  // input -> hex
O(Sz)   // Only letters?

```

Try it online (slightly modified version that works on web)
> 11 votes

# Answer
# MATL, 10

```
i16YA1Y2mA

```

### Examples

```
>> matl i16YA1Y2mA
> 240
0
>> matl i16YA1Y2mA
> 255
1

```

### Explanation

```
i       % input
16YA    % convert to string representation in base 16
1Y2     % predefined literal: 'A':'Z'
m       % true for set member
A       % all

```

---

# Bonus challenge: 53−40 = 13

```
i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]

```

### Examples

```
>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 >
> 255
Only letters

>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 >
> 100
Only numbers

>> matl
 > i16YA1Y2mXKA?'Only letters'}Ka?'Mix'}'Only numbers']]
 >
> 240
Mix

```

### Explanation

```
i                       % input
16YA                    % convert integer to string representation in base 16
1Y2                     % predefined literal: 'A':'Z'
m                       % true for set member
XK                      % copy to clipboard K
A                       % all
?                       % if (top of the stack)
  'Only letters'        % string literal
}                       % else
  K                     % paste from clipboard K
  a                     % any
  ?                     % if (top of the stack)
    'Mix'               % string literal
  }                     % else
    'Only numbers'      % string literal
  ]                     % end
]                       % end

```
> 8 votes

# Answer
# Python 3, ~~30~~ 29 bytes

1 byte stripped thanks to sysreq and Python 3.

```
lambda n:hex(n)[2:].isalpha()

```

Simple `lambda` and slicing.
> 8 votes

# Answer
# LabVIEW, 52-40 = 12 LabVIEW Primitives

Praise the built-ins!
> 8 votes

# Answer
# C, ~~46~~ ~~43~~ 37 bytes

Now with more recursion! (Thanks Dennis):

```
F(x){return(x%16>9)*(x<16?:F(x/16));}

```

Bonus: even shorter (33 bytes), but fails for `x = 0`:

```
F(x){return!x?:(x%16>9)*F(x/16);}

```

---

```
b;F(x){for(b=x;x;x/=16)b*=x%16>9;return b;}

```

`F()` takes an `int` and returns either `0` (false) or non-zero (true).

I didn't even try to achieve the bonus, `"MixOnly lettersnumbers"` takes 23 bytes alone, tracking the new condition would have required 9 additional bytes, `printf()` is 8 bytes, which adds up to 40, nullifying the effort.

Test main:

```
#include <stdio.h>

int main() {
  int testdata[] = {10, 100, 161, 11259375, 0};
  for (int i = 0; i < 5; ++i) {
    int d = testdata[i];
    printf("%d (0x%x) -> %s\n", d, d, F(d)?"yep":"nope");
  }
}

```
> 8 votes

# Answer
## Mathematica, 32 bytes

```
Tr@DigitCount[#,16,0~Range~9]<1&

```

Explanation:

```
                               &   A function returning whether
Tr@                                 the sum of elements of
   DigitCount[ ,  ,         ]        the numbers of
                   0~Range~9          zeros, ones, ..., nines in
                16                    the hexadecimal expansion of
              #                       the first argument
                             <1     is less than one.

```
> 7 votes

# Answer
# Julia, 18 bytes

```
n->isalpha(hex(n))

```

This is an anonymous function that accepts an integer and returns a boolean. To call it, give it a name, e.g. `f=n->...`.

The input is converted to a hexadecimal string using `hex`, then we check whether its entirely comprised of alphabetic characters using `isalpha`.
> 7 votes

# Answer
# Perl 6, 18 bytes

```
{.base(16)!~~/\d/} # 18 bytes

```

usage:

```
# give it a name
my &code = {.base(16)!~~/\d/}

for 10, 100, 161, 11259375, 0 {
  printf "%8s %6s %s\n", $_, .base(16), .&code
}

      10      A True
     100     64 False
     161     A1 False
11259375 ABCDEF True
       0      0 False

```
> 7 votes

# Answer
# Javascript, ES6, no regexp, 28 bytes

```
F=n=>n%16>9&&(n<16||F(n>>4))

```

There's also this 27-byte version but it returns the inverse value.

```
F=n=>n%16<10||n>15&&F(n>>4)

```
> 7 votes

# Answer
# JavaScript ES6, 29

No bonus

```
n=>!/\d/.test(n.toString(16))

```

With the new value of **-40** the bonus is nearer now ... but not enough. Bonus score 70 ~~71~~ \- 40 =\> **30 ~~31~~**

```
n=>/\d/.test(n=n.toString(16))?1/n?'Only numbers':'Mix':'Only letters'

```

Test snippet (type a number inside the input box)

```
#I { width:50%}
```

```
<input id=I oninput="test()"/><br>
Hex <span id=H></span><br>
Result <span id=R></span>
```
> 6 votes

# Answer
# GS2, 6 bytes

```
V↔i/◙s

```

The source code uses the CP437 encoding. Try it online!

### How it works

```
V       Evaluate the input.
 ↔      Push 16.
  i     Perform base conversion.
   /    Sort.
    ◙   Push [10].
     s  Perform greater-or-equal comparison.

```
> 4 votes

# Answer
# Java, ~~46~~ ~~44~~ 38 bytes

```
i->i.toHexString(i).matches("[a-f]+");

```

Pretty simple one-liner that converts the integer to a hexadecimal string and uses regex to determine if all characters are letters.

-2 bytes thanks to @Eng.Fouad.
> 4 votes

# Answer
# Octave, 22 bytes

```
@(n)all(dec2hex(n)>64)

```
> 4 votes

# Answer
# Ruby, 19 bytes

```
->n{!('%x'%n)[/\d/]}

```

**Ungolfed:**

```
-> n {
  !('%x'%n)[/\d/]
}

```

**Usage:**

```
f=->n{!('%x'%n)[/\d/]} # Assigning it to a variable
f[0]
=> false
f[10]
=> true
f[100]
=> false
f[161]
=> false
f[11259375]
=> true

```

**With bonus, 70 - 40 = 30 bytes**

```
->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'}

```

**Usage:**

```
f=->n{'%x'%n=~/^(\d+)|(\D+)$/;$1?'Only numbers':$2?'Only letters':'Mix'}
f[10]
=> Only letters
f[100]
=> Only numbers
f[161]
=> Mix

```
> 4 votes

# Answer
## CJam (9 8 bytes)

```
{GbA,&!}

```

Online demo
> 3 votes

# Answer
## Perl, 69 - 40 = 29 bytes

```
$_=sprintf"%X",<>;print s/\d//?$_?"Mix":"Only numbers":"Only letters"

```
> 3 votes

# Answer
# SmileBASIC 3.2.1, 78 bytes

```
INPUT V FOR I=0 TO 9
IF INSTR(HEX$(V),STR$(I))>-1 THEN ?"FALSE"END
NEXT?"TRUE"

```
> 2 votes

# Answer
## Ceylon, 55 bytes

```
Boolean l(Integer n)=>!any(formatInteger(n,16)*.digit);

```

Straightforward ... we format `n` as a hexadecimal number (which produces a string), call on each character of that string the `.digit` number (which returns true if it is a digit), then check whether any of them are true, then negate this.

The version with bonus has a lot higher score of **119 - 25 = 94**:

```
String c(Integer n)=>let(s=formatInteger(n),d=s*.digit)(every(d)then"Only numbers"else(any(d)then"Mix"else"Only letters"));

```

I'm not sure how anyone could make a bonus version short enough to be better than the no-bonus version, even those strings alone have length 28 together. Maybe a language which makes it really hard to produce a truthy/falsey value.

Here is a formatted version:

```
String c(Integer n) =>
        let (d = formatInteger(n,16)*.digit)
    (every(d) then "Only numbers"
                else (any(d) then "Mix"
                    else "Only letters"));

```
> 2 votes

# Answer
## Seriously, 12 bytes

```
4ª,¡OkúOkd-Y

```

Hex Dump:

```
34a62cad4f6b
a34f6b642d59

```

Try It Online

It's the same as the other stack language answers. It would be only 7 bytes if Seriously supported string subtraction yet.

EDIT: Seriously now supports string subtraction and the following 7 byte solution now works:

```
ú4╙,¡-Y

```

Hex Dump:

```
a334d32cad2d59

```

Try It Online
> 2 votes

# Answer
## Rust, 70 bytes

```
fn f(n:i32)->bool{format!("{:x}",n).chars().all(|c|c.is_alphabetic())}

```

Because, ya know, ~~Java~~ Rust.

It's actually quite elegant, though:

```
format!("{:x}", n)         // format n as hex (:x)
  .chars()                 // get an Iter over the characters
  .all(                    // do all Iter elements satisfy the closure?
    |c| c.is_alphabetic()  // self-explanatory
  )

```

But it's a shame the function definition boilerplate is so long.... :P
> 2 votes

# Answer
# CJam, 44 bytes - 40 bonus = 4 bytes

```
2,riGbAf/&:-"Only numbersOnly lettersMix"C/=

```

Try it here~
> 2 votes

# Answer
# 05AB1E, 2 bytes

Code:

```
ha

```

Ha! That is two bytes! ~~Sadly non-competing because this language postdates the challenge :(~~

Explanation:

```
h   # Convert input to hexadecimal
 a  # is_alpha, checks if the value only contains letters

```

Try it online! or Verify all test cases!
> 2 votes

# Answer
# Ruby, 16 bytes

```
->n{/\d/!~'%x'%n}

```

# Ruby, 70 bytes - 40 bonus = 30

```
f=->n{s="Only #{n%16<10?:Numbers:'Letters'}";n<16||s==f[n/16]?s:'Mix'}

```
> 2 votes

# Answer
# Python 3, 28 bytes

```
lambda x:min(hex(x)[1:])>'@'

```
> 2 votes

# Answer
# Common Lisp, 40 bytes

```
(every'alpha-char-p(format()"~x"(read)))

```

Try it online!
> 2 votes

# Answer
## PHP, ~~56~~ 44 bytes

This isn't going to win, but might as well. Takes one command-line argument.

Thank you @Blackhole for reducing this by 12 bytes.

```
<?=ctype_lower(base_convert($argv[1],10,16))

// Previous attempt, 56 bytes
<?=preg_match('#^[a-f]+$#',base_convert($argv[1],10,16))

```
> 1 votes

# Answer
# Japt, 12 bytes

```
!UsG r"[a-f]

```

Try it online!

### How it works

```
!UsG r"[a-f] // Implicit: U = input integer, G = 16
 UsG         // Convert U to a base-16 string.
     r"[a-f] // Replace all lowercase letters with an empty string.
!            // Take the logical NOT of the result.
             // This returns true for an empty string; false for anything else.

```
> 1 votes

# Answer
## Haskell, 39 bytes

```
p n|mod n 16<10=0|n<16=1|1<2=p$div n 16

```

Returns `0` or `1`. Usage example:

```
*Main> map p [10,100,161,11259375,0]
[1,0,0,1,0]

```

Haskell has neither built-in base conversion nor check for letters. Both functions are in modules where the imports alone would cost 36 bytes, so that's not an option. Instead I check the input number `n` for:

1. if `mod n 16` is less than `10` -\> False
2. if `n` is less than `16` -\> True
3. otherwise re-check with `n/16`.
> 1 votes

# Answer
# C, 132 bytes

```
int main(){int a=0,p=1;char b[256];scanf("%d",&a);sprintf(b,"%x",a);for(char*c=b;*c!='\0';c++)if(isdigit(*c)){printf("False");p=0;}if(p)printf("True");return 0;}

```

**Detailed**

```
int main()
{
    int a=0, p=1;
    char b [256];

    scanf("%d",&a); // read input as an integer
    sprintf(b,"%x",a); // read in Hex into string

    for(char * c=b; *c!='\0'; c++)
    {
        if(isdigit(*c)) // if it's a digit
        {
            printf("%x No",a);
            p=0;
        }
    }

    if(p) // if no digit was found
    {
        printf("%x Yes",a);
    }

    return 0;
}

```

**Bonus, 232 - 40 = 192 bytes**

```
int main(){int a=0, p=0,q=0;char b [256];scanf("%d",&a);sprintf(b,"%x",a);for(char * c=b; *c!='\0'; c++) if(isdigit(*c)) p=1; else q=1;if(p&&q) printf("Mixed");else if(p) printf("Only numbers");else printf("Only letters");return 0;}

```

**Detailed**

```
int main()
{
    int a=0, p=0,q=0;
    char b [256];

    scanf("%d",&a);
    sprintf(b,"%x",a);

    for(char * c=b; *c!='\0'; c++) if(isdigit(*c)) p=1; else q=1;

    if(p&&q) printf("Mixed");
    else if(p) printf("Only numbers");
    else printf("Only letters");

    return 0;
}

```
> 1 votes

# Answer
# Gema, 41 characters

```
*=@c{@radix{10;16;*}}
c:<D>=f@end;?=;\Z=t

```

There is no boolean in Gema, so it simply outputs “t” or “f”.

Sample run:

```
bash-4.3$ echo -n '11259375' | gema '*=@c{@radix{10;16;*}};c:<D>=f@end;?=;\Z=t'
t

```
> 1 votes

# Answer
# Perl, 24 bytes

```
$_=sprintf"%x",$_;$_=/\D/&/\d/?Mix:Only.$".(/\d/?numb:lett).ers

```

Code is 63 bytes, add 1 for the `-p` flag, and then subtract 40 for the bonus.
> 1 votes

# Answer
# Binary-Encoded Golfical, 50+1 (`-x` flag)=51 bytes

Noncompeting; the modulo instruction used here, although it was added to the specs, according the repo's revision history, on the same day this question was posted, was for some reason never implemented until earlier today.

Hexdump:

```
00 C0 03 15 14 14 1B 1A 14 08 01 14 17 00 10 14
00 01 0A 01 21 1E 2C 3D 14 53 2D 14 08 01 0A 01
1C 00 0A 00 10 17 0A 01 08 01 00 00 26 14 1E 1C
1D 14

```

This encoding can be converted back to the original graphical form using the included Encoder utility, or run directly by adding the `-x` flag.

Original image:

Magnified 50x:

Rough translation:

```
prompt *p
label A
push *p
*p%=16
if *p<10
 print 0
 exit
endif
*p=pop
*p/=16
if *p==0
 print 1
 exit
endif
goto A

```
> 1 votes

# Answer
# PHP, 32 bytes

since rink.attendant.6 won´t react; I post my own.

```
echo+ctype_alpha(dechex($argn));

```

takes input from STDIN; prints `1` or `0`; run with `-R`.

**bonus attempt, ~~93~~ 87-40=47**
5 bytes saved by Jörg, 1 by me

```
echo(ctype_alpha($s=dechex($argn))+$d=ctype_digit($s))?"Only ".[lett,numb][$d].ers:Mix;

```

takes input from STDIN; run with `-nR`.

btw. `ctype_xdigit` would be an option for `Mix` and help serialize (though `pi` is the shortest alternative); but I guess it can´t get any shorter than Jörgs idea with my golfing.
The more you serialize, the longer it gets.

a **partly serialized** version for ~~101~~ 100-40=60:
2 bytes saved and 1 byte fixed by Jörg

```
echo strtr([ctype_alpha($s=dechex($argn))=>_letters,ctype_digit($s)=>_numbers,Mix][1],[_=>"Only "]);

```

and **fully serialized** for ~~114~~ 112-40=72:
-2 bytes inspired by Jörg

```
foreach([pi=>Mix,ctype_alpha=>lett,is_numeric=>numb]as$f=>$t)$f(dechex($argn))&&$s=$t<a?$t:"Only $t".ers;echo$s;

```
> 1 votes

# Answer
# Thunno 2, 30 bytes \- 40 = -10

```
ḤDA?‘Ṇß ɱṀ‘ʂ:dAS?ʋMix:‘Ṇß ḶẸ‘ʂ

```

Try it online!

## Thunno 2, 2 bytes

```
ḤA

```

Try it online!

#### Explanation

```
Ḥ               # Convert to hexadecimal
 D              # Duplicate it
  A             # Is it all alphabetic?
   ?            # If it is:
    ‘Ṇß ɱṀ‘ʂ    #  Push compressed string "Only letters"
            :   # Otherwise:
             dA #  Check if each character is alphabetic
S?              #  If at least one is true:
  ʋMix          #   Push the string "Mix"
      :         #  Otherwise:
       ‘Ṇß ḶẸ‘ʂ #   Push compressed string "Only numbers"

```

```
Ḥ   # Convert to hexadecimal
 A  # Is it all alphabetic?

```
> 1 votes

# Answer
# Swift 5.9, ~~61~~ ~~58~~ 51 bytes

```
let l={String($0+0,radix:16).allSatisfy(\.isCased)}

```

I chose to use `isCased` rather than `isLetter` in order to save a byte.
> 1 votes

# Answer
## CoffeeScript, ~~42~~ 36 bytes

```
f=(x)->/^[a-f]+$/.test x.toString 16

// Previous attempt (42)
f=(x)->!x.toString(16).replace /[a-f]/g,''

```

---

## JavaScript (ES6), ~~41~~ 36 bytes

```
f=x=>/^[a-f]+$/.test(x.toString(16))

// Previous attempt (41)
f=x=>!x.toString(16).replace(/[a-f]/g,``)

```
> 0 votes

# Answer
# R, 34 bytes

```
!grepl("\\d",sprintf("%x",scan()))

```

`scan()` takes an integer from stdin, `sprintf("%x",...)` returns the hexadecimal representation of that integer (R's `sprintf` is equivalent to C's `sprintf`), then the regex checks if the string contains digits.

Usage:

```
> !grepl("\\d",sprintf("%x",scan()))
1: 100
2:
Read 1 item
[1] FALSE
> !grepl("\\d",sprintf("%x",scan()))
1: 10
2:
Read 1 item
[1] TRUE
> !grepl("\\d",sprintf("%x",scan()))
1: 161
2:
Read 1 item
[1] FALSE
> !grepl("\\d",sprintf("%x",scan()))
1: 11259375
2:
Read 1 item
[1] TRUE
> !grepl("\\d",sprintf("%x",scan()))
1: 0
2:
Read 1 item
[1] FALSE

```
> 0 votes

# Answer
# , 9 chars / 16 bytes

```
!ïⓧċ/[α]⌿

```

`Try it here (Firefox only).`

Regex aliases ftw!

# Explanation

```
        // Implicit: ï = input
!       // logical-negate the result of the following code:
 ïⓧ    // convert ï to hex...
 ċ/[α]⌿ // and see if it has any letters
        // implicit output

```
> 0 votes

# Answer
## Pyke, 6 bytes

```
b16G-!

```

Try it here!

Or 10 bytes with the bonus

```
b16\9L>]0}DlRs*"Only numbers,Only letters,Mix"\,c@

```

Explanation:

```
b16                                                -      base_16(input())
   \9L<                                            -     map("9">char for char in ^)
       ]0                                          -    list(^)
         }                                         -   set(^)
          DlRs*                                    -  len(^)*sum(^)
                                                 @ - V[^]
               "Only numbers,Only letters,Mix"\,c  -  str.split(",")

```

Try it here!
> 0 votes

# Answer
# SmileBASIC, ~~52~~ 50 bytes

```
INPUT V
H$=HEX$(V)WHILE""<H$P=@A<POP(H$)||P
WEND?P

```

Determines if each digit is a number or letter by comparing it with `@A` (the A doesn't matter since it would only look at it if the first characters were the same). `@` is between the number and the letters in ASCII.
> 0 votes

# Answer
# MATL, 7 bytes

```
1YAtk=~

```

Explanation:

```
1       % number literal
YA      % convert integer to string representation in given base (16)
t       % duplicate elements
k       % convert (the second) string to lowercase
=       % is equal?
~       % logical 'not' (element-wise)
        % (implicit) convert to string and display

```

For only letters to be in the base-16 representation, when the string is made lowercase every character must have changed, so the arrays should never be equal to each other, and only arrays of ones are truthy in MATL.

# Bonus challenge, 47-40 = 7 bytes:

```
1YAtk=XK?'Only numbers'}Ka?'Mix'}'Only letters'

```

Essentially the same as the other MATL answer given, the same ending was used just without trailing `]]` and with reordering the outputs.
> 0 votes

# Answer
# Befunge (quirkster flavor), 34 bytes

```
&:44*%9`!#@ #. #0_44*/:!#@ #. #1_#

```

Befunge control flow loops around to the beginning when it hits the end, so a recursive solution is pretty natural. If the input is less than 9 modulo 16, print 0 (the only falsey value in Befunge) and exit. If not, divide the number by 16, rounding down. If it's now 0, print 1 and exit, otherwise recurse. In effect, this checks each hex digit from right to left.
> 0 votes

# Answer
## Clojure, 35 bytes

```
#(every?(set"abcdef")(format"%x"%))

```
> 0 votes

# Answer
# tcl, 35

```
puts [string is alp [format %x $n]]

```

demo
> 0 votes

# Answer
# Pushy, 16 bytes

```
$&16%v16/;OKT)P#

```

**Try it online!**

Essentially calculates all digits as numbers `0-16`, and then checks they are all over 10.

```
                    \ Implicit: Input on first stack
$        ;          \ While input != 0:
 &16%v              \   Push input % 16 to second stack
      16/           \   Floordiv input by 16
          O         \ Go to second stack
           KT)      \ Map all numbers to boolean: bigger than 10?
              P     \ Get the product (only 1 if all values are 1)
               #    \ Print result.

```
> 0 votes

# Answer
# Excel, 121 bytes

```
=LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(DEC2HEX(A2),"A",),"B",),"C",),"D",),"E",),"F",))=0

```

Nothing graceful about this one.
> 0 votes

# Answer
# Scala 3, 32 bytes

```
_.toHexString.forall(_.isLetter)

```

Attempt This Online!
> 0 votes

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


title: Tips for golfing in Swift

text:
# Question
Title: Tips for golfing in Swift
What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications?

Please post one tip per answer.

# Answer
> 7 votes
# Ranges

One thing that is really helpful is creating ranges using the `...` or `..<` operators

For example

```
array[0..<n] //first n elements of array
array[k..<n] //kth through nth elements of array
array[k...n] //kth through n-1 elements of array

```

So, to get the 2nd through 4th values of an array

```
let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"]
print(myArray[1..<4]) //["cd", "ef", "gh"]

```

### Practical Use

```
let a = [3, 1, 4, 1, 5, 9]

```

Using

```
for v in a[0...3]{print(v)}

```

Is 8 bytes shorter than

```
for n in 0...3{let v=a[n];print(v)}

```

# Answer
> 7 votes
# Closures:

The use of variables the hold a function vs. using a function itself can help:

**65 bytes:**

```
var r:(String,Int)->String={return String(repeating:$0,count:$1)}

```

**66 bytes:**

```
func r(s:String,i:Int)->String{return String(repeating:s,count:i)}

```

Small difference here, but it'll show more in some puzzles.

# Shortening Functions:

Looking at the previous example reminds me of something. Sometimes, if you will be using a function enough times, it is worth the space to rename it:

This:

```
String(repeating:$0,count:$1)

```

To this:

```
var r:(String,Int)->String={return String(repeating:$0,count:$1)}

```

Or, actually, this is better:

```
var r=String.init(repeating:count:)

```

That way you just call `r("Hello World",8)` instead of `String(repeating:"Hello World",count:8)`

# Leaving Out Type Declarations:

I once created a closure without setting the argument type, thus creating a shorter answer:

```
var f={(i)->Int in i-1+i%2*2}

```

*The compiler inferred that `i` is in `Int`.*

# Create Arrays the Fast Way:

If you need an array of `Ints`, use a `Range` to create it:

```
Array(0...5)

```

This does the same thing as:

```
[0,1,2,3,4,5]

```

# Arrays Instead of `If` or `Switch`:

Instead of doing this:

```
if n==0{return "a"}else if n==1{return "b"}else{return "c"}

```

You can probably do this:

```
return ["a","b","c"][n]

```

# Shorten Types:

If you are using type conversion a lot, you might want to create a type alias:

```
typealias f=Float

```

# Map:

Remember that you often don't need to use the `return` keyword in the `map` function.

# Running Swift Online:

Although Try It Online does not support Swift It does now!

# Answer
> 6 votes
# Getting Rid of Argument Labels

Argument labels eat up a lot of characters:

```
String(repeating:"-",count:81)

```

```
g.joined(separator:"")

```

But function types in Swift have no argument labels, so if we use the function type instead of the initializer/method directly, we don't need argument labels. The shortest way I know is to put the initializer/method in a closure, then call the closure, and immediately call the resulting function:

```
{String.init}()("-",81)

```

```
{g.joined}()("")

```

This works for overloaded methods as well, as long as the compiler can infer the method to call from the parameter types.

# Answer
> 4 votes
## `try`

In Swift 2.x and above, functions that traditionally handled errors by passing a pointer to an `NSError` object as a function parameter now `throw` their error.

This means that this:

```
var regex = NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: nil, error: nil)

```

now looks like:

```
do {
    let regex = try NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])
} catch {
    print(error)
}

```

This can be shortened by using `try?` or `try!`. `try?` will evaluate the expression to `nil` if an error is thrown. `try!` will crash your program if an error is thrown, and should be only used in cases where there will never be an error thrown.

```
let regex = try! NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])

```

`try?` and `try!` save at least 13 bytes from the `do-try-catch` loop. Note that you also save at least one more byte by passing in an empty array (`[]`) for options instead of `nil` as well.

# Answer
> 4 votes
## Reducing Arrays

Iterating with `for-in loops` through an array to get a single value such as the sum of the elements inside, or the product of its elements may be too long for how simple it actually is. You can just use the `reduce()` method. Some examples:

```
var array = [1,2,3,4,5,6,7]

```

Adding up the elements in an array with `for-in` loops:

```
var sum = 0

for item in array{
    sum += item
}
print(sum)

```

can be simplified to:

```
print(array.reduce(0, +))

```

And getting the product of the elements inside of the array with for-in loops:

```
var multiplier = 1
for item in array{
    multiplier *= item
}
print(multiplier)

```

can also be reduced to:

```
print(array.reduce(1, *))

```

# Answer
> 3 votes
## Substring

Sometimes, you can save bytes by falling back onto Foundation types instead of using pure Swift types. Compare accessing a substring of an `NSString` vs a Swift `String` type:

```
let x:NSString = "hello world"
x.substringToIndex(5) // "hello"

let y = "hello world"
y.substringToIndex(y.startIndex.advancedBy(5)) // "hello"

```

Even with the 9 characters lost by declaring `x` as an `NSString`, you save 25 more by using the Foundation type, since `substringToIndex` takes an `Int` as a parameter for `NSString`, vs an `Index` struct (`String.CharacterView.Index`) for Swift `String` types.

I should note that the availability of Foundation types may differ across multiple platforms (OS X, Linux, etc). Most Foundation classes are `NSUnimplemented` in the open-source version of Swift.

# Answer
> 3 votes
# Enumeration

You can chain `forEach` from `enumerated()` on a collection type to get a reference to the object (or value type) in a collection, as well as its index:

```
[1,2,3,4,5].enumerated().forEach{print($0,$1)}

```

or

```
for (c,i) in [1,2,3,4,5].enumerated(){print(c,i)}

```

or (even shorter `CountableClosedRange` syntax)

```
(1...5).enumerated().forEach{print($0,$1)}

```

Prints:

```
0 1
1 2
2 3
3 4
4 5

```

# Answer
> 3 votes
# .map()

Combining `.map()` with trailing closure syntax can tighten up for-loops. We can put the things we want to iterate over into an array, then use `.map()` to perform some action on each element.

For example, we can use `.map()` to write that old chestnut, Fizzbuzz, in one line.

```
var d: [Int] = Array(1...100)

d.map{$0%15 == 0 ? print("Fizzbuzz") : $0%3 == 0 ? print("Fizz") : $0%5 == 0 ? print("Buzz") : print($0)}

```

Outside of golf, `.map()` can help cut down on repetition. For example, suppose you have a view you need to position programmatically. You can put the anchors for the view into an anonymous array and run `.map()` over it to set each constraint's `.isActive` to true, like so:

```
_ = [
        view.topAnchor.constraint(equalTo: view.topAnchor, constant: 40),
        view.widthAnchor.constraint(equalTo: view.widthAnchor),
        view.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ].map { $0.isActive = true }

```

# Answer
> 3 votes
# Golfing variable assignments in control flow structures using tuples

Consider you want to use a `while` loop, and you want to use the same thing in both the condition and the block to follow. Then, an inline assignment in a tuple would most likely help. The longer your attribute, the better! Consider this (3 bytes shorter):

```
func f(s:[Int]){var k=s,i=0;while(i=k.count,i>0).1{print(i,i+k[i-1]);k.removeLast();}}

```

over this:

```
func g(s:[Int]){var k=s,i=0;while k.count>0{i=k.count;print(i,i+k[i-1]);k.removeLast();}}

```

Notice the `(i=k.count,i>0).1` part, which is quite interesting.

---

Inspired by one of Herman Lauenstein's answers.

# Answer
> 3 votes
# Import

You can replace `import Foundation` with `import UIKit` for 5 bytes shorter, as UIKit does import Foundation already.

# Answer
> 2 votes
Swift's ternary operator is very terse: `condition ? action : other`action

If the condition is true, do one thing, if not, do something else.

```
textColor = bgIsBlack ? .white : .black

```

This makes the `textColor` white if the background is black, or black if the background is any other color.

The nil coalescing operator is even terser: `a ?? b`

Let's say you're checking JSON for a certain key so you can present the key's value as title text. If the key isn't present (i.e value is nil), we want to give the title default text.

```
title = keysValue ?? "Not Available"

```

# Answer
> 2 votes
# Repeating Strings

Unfortunately, Swift does not support String multiplication with `*`, likewise Python. A good method you can use instead is `String(repeating:count:)`, but unfortunately that's not really golfy. Compare these two approaches:

```
var a=String(repeating:"abc",count:3)

```

and

```
var a="";for _ in 0..<3{a+="abc"}

```

The second one is a couple of bytes shorter, but that cannot be used in a closure... Better yet, and it also works in closures:

```
(0..<3).map{_ in"abc"}.joined()

```

And what if I do it multiple times? Well, you can use `String.init()`. Now, this may save lots of bytes. For example (68 bytes):

```
let k=String.init(repeating:count:)
print(k("abcd",9)+k("XYZxyz",9))

```

instead of (74 bytes):

```
print(String(repeating:"abcd",count:9)+String(repeating:"XYZxyz",count:9))

```

or (70 bytes):

```
var f={String(repeating:$0,count:$1)}
print(f("abcd",9)+f("XYZxyz",9))

```

But make sure your String is long enough. If you are using `String(repeating:"abc",3)`, it is *much* better to use `"abcabcabc"` instead.

# Answer
> 2 votes
# Type Inference

Swift's type checker is very good at inferring types — a blessing like no other when golfing — but sometimes it needs a little help. Consider this code (borrowed from one of my own answers):

```
let function = { (decoy: String, target: String) in
  let array = ([decoy] + { [String].init }()(target, 511)).shuffled()
  // ...
}

```

(For context, this creates a 512-element array where all but one of the elements are identical.)

Thanks to closure tricks, this is already pretty golfy once whitespace is removed and names are shortened:

```
let f={(d:String,t:String)in let a=([d]+{[String].init}()(t,511)).shuffled()
/* ... */}

```

But there are three words that stick out like sore thumbs, and they all start with an `S` and end with a `tring`. Thankfully, we can get rid of all three by combining two more tricks.

## Type Placeholders (Swift 5.6 and newer)

If the type checker can't infer an entire type on its own, but it can infer some of its type parameters (i.e. things like the `T` in `SomeType<T>`), then you can replace those parameters with an underscore to tell the type checker to figure them out for you. For instance, `Array<String>` can become `Array<_>` (as long as something else makes it clear that the type parameter is a `String`).

> Of course, this also applies to the syntactic sugar versions of `Array<Element>`, `Dictionary<Key, Value>`, and `Optional<Wrapped>`, as well as tuple types, function types, and anything else that counts as a type. So `[String]` can be replaced with `[_]` in much the same manner.

Taking advantage of this, we can save 5 bytes in our example:

```
let f={(d:String,t:String)in let a=([d]+{[_].init}()(t,511)).shuffled()
/* ... */}

```

Now we've got the other two to deal with. We can't use the type placeholder trick with these, since the type checker will then struggle with just about everything. So we've got to hint at these types another way...

## Appending Literals

Let's start with an absolutely horrible example that still illustrates the point well:

```
let p={(n:Int)in print(n)}

```

Let's say you want to get rid of the bulky `Int` type signature. You can't just outright remove it, because then the type checker won't have any way of knowing that `n` is an `Int`. So you need to give it some other, shorter way of figuring the type out.

One way to do this is by doing something with the value that doesn't affect how the program runs, but still makes it clear what the type is. In this instance, you can simply add `0` to `n`:

```
let p={n in print(n+0)}

```

> Since we no longer have to declare any explicit types, we can do away with the closure header altogether and use implicit closure parameters instead:
>
> ```
> let p={print($0+0)}
>
> ```
>
> Note, however, that this only saves bytes if you only use each parameter once or twice, and that implicit parameters can't be used inside of other closures.

Here's a table of literals you can use in this manner:

| Type | Type Hint |
| --- | --- |
| `Array` | `$0+[]` |
| `Dictionary` | `$0+[:]` |
| `String` | `$0+""` |
| `Int` | `$0+0` |
| `Double` | `$0+0.0` |

Using these, our first example can be reduced to:

```
let f={d,t in let a=([d+""]+{[_].init}()(t,511)).shuffled()
/* ... */}

```

> `t` can be inferred on its own without a problem here, so we don't need to append an empty literal to it.

With implicit closure parameters, we can make this even smaller:

```
let f={let a=([$0+""]+{[_].init}()($1,511)).shuffled()
/* ... */}

```

# Answer
> 1 votes
# Conversion to string

When possible, it is shorter to use string interpolation than to use the `String` method for converting to a string.

```
String(a)

```

vs

```
"\(a)"

```

# Answer
> 0 votes
# Boolean Literals

Instead of using Boolean literals, which take up 4 or 5 bytes, use a 3-byte comparison instead.

| Literal | Comparison | Bytes Saved |
| --- | --- | --- |
| `true` | `0<1` | 1 |
| `false` | `0>1` | 2 |

---
Tags: code-golf, tips, swift
---


title: Calculate Home Primes

text:
# Question
Title: Calculate Home Primes
The Home Prime of an integer \\$n\\$ is the value obtained by repeatedly factoring and concatenating \\$n\\$'s prime factors (in ascending order, including repeats) until reaching a fixed point (a prime). For example, the Home Prime (\\$\text{HP}(n)\\$) of \\$10\\$ is \\$773\\$ as:

$$\begin{align} 10 & = 2 \times 5 \to 25 \\ 25 & = 5 \times 5 \to 55 \\ 55 & = 5 \times 11 \to 511 \\ 511 & = 7 \times 73 \to 773 \\ \end{align}$$

There are two equivalent ways to consider when the sequence ends:

* It ends at a prime
* It reaches a fixed point, as the prime factors of a prime \\$p\\$ is just \\$p\\$

Note that the Home Prime of some numbers is currently unknown (e.g. \\$49\\$ or \\$77\\$).

---

You are to take a positive integer \\$n \ge 2\\$ as input through any convenient method or format and output the Home Prime of \\$n\\$. You may assume that you don't have to handle any input that would exceed the integer limit in your language at any step, and you may assume that the input will already have a known Home Prime (so 49 won't be an input).

Make sure you program handles all inputs correctly, not just those that are only semiprimes:

$$\begin{align} \text{HP}(24) = 331319 :\\ 24 & = 2 \times 2 \times 2 \times 3 \to 2223 \\ 2223 & = 3 \times 3 \times 13 \times 19 \to 331319 \end{align}$$

This is so the shortest code in bytes wins!

## Test cases

These are the results for each \\$2 \le n \le 100\\$, excluding \\$n = 49,77,80,96\\$ which don't terminate on TIO in my example program.

```
  2                                  2
  3                                  3
  4                                211
  5                                  5
  6                                 23
  7                                  7
  8                3331113965338635107
  9                                311
 10                                773
 11                                 11
 12                                223
 13                                 13
 14                              13367
 15                               1129
 16                           31636373
 17                                 17
 18                                233
 19                                 19
 20                3318308475676071413
 21                                 37
 22                                211
 23                                 23
 24                             331319
 25                                773
 26                               3251
 27                              13367
 28                                227
 29                                 29
 30                                547
 31                                 31
 32                             241271
 33                                311
 34                              31397
 35                               1129
 36                              71129
 37                                 37
 38                                373
 39                                313
 40                      3314192745739
 41                                 41
 42                                379
 43                                 43
 44                        22815088913
 45                            3411949
 46                                223
 47                                 47
 48             6161791591356884791277
 50                               3517
 51                                317
 52                               2213
 53                                 53
 54                               2333
 55                                773
 56                              37463
 57                               1129
 58                                229
 59                                 59
 60                              35149
 61                                 61
 62                              31237
 63                                337
 64                      1272505013723
 65 1381321118321175157763339900357651
 66                               2311
 67                                 67
 68                               3739
 69                              33191
 70                                257
 71                                 71
 72                            1119179
 73                                 73
 74                                379
 75                                571
 76                             333271
 78                         3129706267
 79                                 79
 81                    193089459713411
 82                                241
 83                                 83
 84                               2237
 85                               3137
 86          6012903280474189529884459
 87         41431881512748629379008933
 88                             719167
 89                                 89
 90                              71171
 91                          236122171
 92                             331319
 93                                331
 94                               1319
 95                              36389
 97                                 97
 98                                277
 99                              71143
100                             317047

```

# Answer
# 05AB1E, 3 bytes

```
ΔÒJ

```

Try it online!

`Δ` run until the output doesn't change:
`Ò` prime factors including duplicates
`J` join into an integer
> 15 votes

# Answer
# JavaScript (ES6),  ~~58~~  55 bytes

```
f=n=>n-(g=d=>q=n>1?n%d?g(d+1):d+g(d,n/=d):'')(2)?f(q):q

```

Try it online!

### Commented

```
f = n =>               // f is a recursive function taking the input n
  n - (                // subtract from n the result of a call to ...
    g = d =>           // ... g: a recursive function taking a divisor d
    q =                //   save in q:
      n > 1 ?          //     if n is greater than 1:
        n % d ?        //       if d is not a divisor of n:
          g(d + 1)     //         increment d until it is
        :              //       else:
          d +          //         append d
          g(d,         //         append the result of a recursive call
               n /= d) //         with n divided by d
      :                //     else:
        ''             //       stop and force coercion to a string
  )(2)                 // initial call to g with d = 2
  ?                    // if it's not equal to n:
    f(q)               //   recursive call to f with n = q
  :                    // else:
    q                  //   we're done: return q

```
> 8 votes

# Answer
# APL(Dyalog Extended), 12 bytes SBCS

```
{⍎⊃,/⍕¨⍭⍵}⍣=

```

Try it on APLgolf!

A dfn submission which takes a single argument.
> 6 votes

# Answer
# Bash, ~~84~~ ~~82~~ 71 bytes

Saved 11 bytes thanks to caird coinheringaahing!!!

```
for((;$1-${2-0};)){ set - `factor $1|sed 's/.*://;s/ //g'` $1;};echo $1

```

Try it online!

Returns the home prime of \\$n\\$ *quickly* (performs all testcase in less than 2 seconds on TIO).
> 5 votes

# Answer
# Haskell, 79 bytes

```
until((==)<*>g)g
g=read.f
f 1=""
f n=[show p++f(div n p)|p<-[2..],mod n p<1]!!0

```

Try it online!

The relevant function is `until((==)<*>g)g`, which takes as input a number `n` and returns its Home prime.
> 4 votes

# Answer
# Vyxal, ~~5~~ 4 bytes

```
‡ǐṅẊ

```

Try it Online!

Jelly really do be getting rekt by stack languages though :p

~~This isn't 4 bytes because strings and integers aren't interchangeable like 05ab1e (and by extension Ohm), but that's okay.~~ I added better type cohesion.

## Explained

```
‡ǐṅẊ
‡ǐṅ  # lambda x: "".join(prime_factorisation(x))
   Ẋ # repeat the above on the input until it doesn't change.

```
> 4 votes

# Answer
# Husk, 6 bytes

```
ω(rṁsp

```

Try it online!

```
ω(        # iterate until reaching a fixed point:
     p    #  get the prime factors
   ṁs     #  convert each to a string & concatenate
  r       #  convert the string to a value

```
> 4 votes

# Answer
# Pyth, 14 bytes

```
W!P_Q=QsjkPQ;Q

```

Try it online!

# Explanation

```
Q     # integer input
W!P_Q # While Q is not prime
=Q    # Set Q to
PQ    # Returns prime factors of Q in increasing order.
k     # Empty string
jk    # Join them
s     # Convert to integer
;     # End of loop
Q     # Print the final value of Q

```
> 3 votes

# Answer
# Ohm v2, 4 bytes

```
·ΘoJ

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

```
ÆfV$ÐL

```

Try it online!

This seems oddly long, but the prime factorize built-in is two bytes, I don't think there's a way to bypass needing the `$`, and the loop-until-not-unique built-in is only one byte long for the accumulator version.
> 3 votes

# Answer
# Python 3, 109 bytes

```
def f(n,m=0):
 while n-m:
  l=m=n;n=0
  for i in range(2,l+1):
   while l%i<1:n=int(f'{n}{i}');l/=i
 return n

```

Try it online!

*Quite* verbose, returns the home prime of \\$n\\$.
> 3 votes

# Answer
# \+ `numbers`, ~~74~~ 73 bytes

```
n=scan();while(F<-el(Reduce(paste0,numbers::primeFactors(n)):0)-n)n=n+F;n

```

Try it online!
> 3 votes

# Answer
# Japt, 12 bytes

```
@=k ¬n)j}a;U

```

Try it

```
@...}a  - first number to return a truthy value when passed trough:
@=        > ignore input and assign 1st input U : *
k ¬n)       * prime factors of U joined and converted to a number
j         > return(is prime?)
;U      - print U

```
> 3 votes

# Answer
# Japt, 11 bytes

```
j ?U:ßUk ¬n
j ?         // If the input is prime
   U        // we're done, return the input.
    :       // Otherwise,
     ß      // recursively rerun
      Uk    // with the input's prime factors
         ¬n // joined together as a string and parsed to a number.

```

Try it here.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 60 bytes

```
#//.x_:>FromDigits[ToString/@(""<>Table@@@FactorInteger@x)]&

```

Try it online!

-14 bytes from @att
> 2 votes

# Answer
# Retina 0.8.2, 37 bytes

```
{`.+
$*_
+`(__+?)(\1)*$
$.1_$#2$*_
_

```

Try it online! Somewhat slow, so link only includes faster test cases. Explanation:

```
{`

```

Repeat until the fixed point.

```
.+
$*_

```

Convert to unary.

```
+`

```

Repeat until all prime factors have been found.

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

```

Find the lowest factor of the remainder.

```
$.1_$#2$*_

```

Prefix the decimal of the factor to the quotient, thus concatenating it to the factors found so far.

```
_

```

Delete the trailing unary `1`.
> 2 votes

# Answer
# Pyth, 5 bytes

```
usjkP

```

Try it online!

Pyth could tie 05AB1E if it had a "join into integer" byte, or Ohm if it could take the primes factors of a string. Beats Jelly even without them, which surprises me.
> 2 votes

# Answer
# Arturo, 49 bytes

```
$->n[until->prime? n[n:do join factors.prime n]n]

```

Try it

Really useful:

* `join [12, 3, 45]` -\> `"12345"`
* `do "12345"` -\> `12345`
> 2 votes

# Answer
# PowerShell, 88 bytes

```
param($n)while($n-ne$m){$m=$n;$n=[int](((factor $m)-replace"^\d+: ").split()-join"")};$n

```

Try it online!

Well, I'm lazy, just ported @Noodle9

# PowerShell, 203 bytes

```
param($k)$s='$f;$n/=$f';function F($n){$m=[math]::sqrt($n);$f=2;while(!($n%$f)){iex $s};$f=3;while($f-le$m-and$n-ge$m){while(!($n%$f)){iex $s};$f+=2};$n};while($k-ne$g){$g=$k;$k=[int]((F($g))-join'')};$k

```

Try it online!

This one has some thought put into it...

`F()` is a function that returns the prime factors of a number, it works like

1. Handle 2 as a prime
2. Then brute force odd numbers
3. Stop when the factor to test exceeds the square root of the number, or the remaining quotient is less than the square root of the number
> 1 votes

# Answer
# Scratch, 320 bytes

Try it online!

Numbers that use values greater than 1 sextillion break because Scratch automatically converts them to scientific notation. Alternatively, 38 blocks.

```
when gf clicked
delete all of[P v
ask()and wait
set[N v]to(answer
repeat until<(length of[P v])=(1
repeat(length of[P v
set[N v]to(join(item(length of[P v])of[P v])(N
delete(length of[P v])of[P v
end
repeat until<(N)=(1
set[F v]to(2
repeat until<((N)/(F))=(round((N)/(F
change[F v]by(1
end
set[N v]to((N)/(F
add(F)to[P v

```
> 1 votes

# Answer
# Japt, 10 bytes

```
@j}a@=k ¬n

```

Try it

# Japt `-h`, 6 bytes

Assumes that it takes no more than `n` iterations to reach `p`.

```
Æ=k ¬n

```

Try it
> 1 votes

# Answer
# Scala, ~~233~~ 212 bytes

saved 21 bytes thanks to the comment of @The Thonnu

Golfed version, try it online!

```
type L=Long
def f(n:L,m:L=0):Long={@scala.annotation.tailrec def g(n:L,m:L):L=if(n==m)n else{var M=n;var N=0L;var l=M;for(i<-2 to l.toInt)while(l%i==0){N=N.toString.concat(i.toString).toLong;l/=i};g(N,M)};g(n,m)}

```

Ungolfed version

```
import scala.annotation.tailrec

object Main {
  def f(n: Long, m: Long = 0): Long = {
    @tailrec
    def innerF(n: Long, m: Long): Long = {
      if (n == m) n
      else {
        var newM = n
        var newN = 0L
        var l = newM

        for (i <- 2 to l.toInt) {
          while (l % i == 0) {
            newN = newN.toString.concat(i.toString).toLong
            l /= i
          }
        }

        innerF(newN, newM)
      }
    }

    innerF(n, m)
  }

  def main(args: Array[String]): Unit = {
    val tests = List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
    val expected = List(2, 3, 211, 5, 23, 7, 3331113965338635107L, 311, 773, 11, 223, 13, 13367, 1129, 31636373, 17, 233, 19, 3318308475676071413L)
    val checker = List("❌", "✓")

    for ((t, e) <- tests.zip(expected)) {
      if (e.toString.length > 10) {
        println(s"$t -> too big")
      } else {
        val s = f(t)
        println(s"$t -> $s ${checker(if (e == s) 1 else 0)}")
      }
    }
  }
}

```
> 1 votes

# Answer
# Uiua SBCS, 13 bytes

```
⍥(⋕/◇⊂°⋕°/×)∞

```

Try it!

```
⍥(⋕/◇⊂°⋕°/×)∞
⍥(         )∞  # to fixed point
        °/×    # factors
      °⋕       # unparse
   /◇⊂         # join all
  ⋕            # parse

```
> 1 votes

# Answer
# APL(NARS), 54 chars

```
⎕fpc←10000⋄g←{¯2↓1⍕{0π⍵:⍵⋄∇{10x⊥⍎¨⍵}↑,/⍕¨k[⍋k]⊣k←π⍵}⍵}

```

The function is a little more long because not all number exit ordered from function π, example

```
   π11613496501723
97 917327 130517

```

see 917327\>130517. I use {10x⊥⍎¨⍵} in place of just ⍎ for problems I don't remember, ({10v⊥⍎¨⍵} not seems right too) and "¯2↓1" because output result with number.0, but somethig easy resolvible.

It is enought fast, the output below in 2 seconds (I not ceck all below numbers only some ones)

```
   ⍪m,¨g¨m←(2..100)∼49 77 80 96
 2  2
 3  3
 4  211
 5  5
 6  23
 7  7
 8  3331113965338635107
 9  311
 10  773
 11  11
 12  223
 13  13
 14  13367
 15  1129
 16  31636373
 17  17
 18  233
 19  19
 20  3318308475676071413
 21  37
 22  211
 23  23
 24  331319
 25  773
 26  3251
 27  13367
 28  227
 29  29
 30  547
 31  31
 32  241271
 33  311
 34  31397
 35  1129
 36  71129
 37  37
 38  373
 39  313
 40  3314192745739
 41  41
 42  379
 43  43
 44  22815088913
 45  3411949
 46  223
 47  47
 48  6161791591356884791277
 50  3517
 51  317
 52  2213
 53  53
 54  2333
 55  773
 56  37463
 57  1129
 58  229
 59  59
 60  35149
 61  61
 62  31237
 63  337
 64  1272505013723
 65  1381321118321175157763339900357651
 66  2311
 67  67
 68  3739
 69  33191
 70  257
 71  71
 72  1119179
 73  73
 74  379
 75  571
 76  333271
 78  3129706267
 79  79
 81  193089459713411
 82  241
 83  83
 84  2237
 85  3137
 86  6012903280474189529884459
 87  41431881512748629379008933
 88  719167
 89  89
 90  71171
 91  236122171
 92  331319
 93  331
 94  1319
 95  36389
 97  97
 98  277
 99  71143
 100  317047

```
> 1 votes

# Answer
# Bash, 99 bytes

```
f(){
a=($(factor $1 | sed 's/^.*: //'))
[ ${#a[@]} -ne 1 ] && f $(tr -d ' '<<<${a[@]}) || echo $a
}

```

Try it online!
> 1 votes

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