# Can the number reach 1 by repeatedly subtracting the largest prime less than it?

## Challenge:

Given a number, take the largest prime strictly less than it, subtract it from this number, do this again to this new number with the biggest prime less than it, and continue doing this until it's less than 3. If it reaches 1, your program should output a truthy value, else, the program should output a falsey value.

## Examples:

All of these should give a truthy value:

3
4
6
8
10
11
12
14
16
17
18
20
22
23
24
26
27
29
30
32
34
35
37
38
40
41
42
44
46
47
48
50


All of these should give falsey values:

5
7
9
13
15
19
21
25
28
31
33
36
39
43
45
49


## Rules:

• You can either write a program or function.
• You can assume that the input is bigger than 2.
• Standard loopholes apply
• This is so the shortest answer wins!
• related oeis.org/A175071 Sep 11, 2016 at 14:10
• 5-3=2, 2-(-2)=4, 4-3=1. (/wiseguy)
– user16488
Sep 11, 2016 at 16:36
• @Hurkyl -2 = -1×2, so it's not prime ;-) Sep 11, 2016 at 19:26
• @ETHProductions: Ah, but -1 is a unit; that factorization doesn't contradict the primality of -2 any more than 2=(-1)×(-2) does of 2. (or even 2=1×2)
– user16488
Sep 11, 2016 at 19:31
• @ETHproductions: The rational numbers are interesting because there are two very different approaches that are useful in practice! The rational numbers has no primes (not even 2!) because everything is a unit. However, you can also view the rationals as a construction made from the integers and study them using the primes of the integers. (e.g. anyone asking for the prime factorization of 9/10 as 2^(-1) 3^2 5^(-1) is thinking in terms of the latter)
– user16488
Sep 12, 2016 at 17:15

# Retina, 31 bytes

.+
$* +1(?!(11+)\1+$)11+
1
^1$ Prints 0 (falsy) or 1 (truthy). Try it online! (The first line enables a linefeed-separated test suite.) ### Explanation .+$*


Convert input to unary by turning input N into N copies of 1.

+1(?!(11+)\1+$)11+ 1  Repeatedly remove the largest prime less than the input. This is based on the standard primality test with regex. ^1$


Check whether the result is a single 1.

• How is it that you can use Retina without unary? O.o Sep 11, 2016 at 12:39
• @Syxer the first two lines convert the input to unary. Sep 11, 2016 at 12:39
• Doesn't that mean you can remove them and request unary input? Sep 11, 2016 at 12:40
• @Syxer I could, but I sort of stopped doing that. It seems like a dodgy I/O format, and now that the conversion is 6 bytes (as opposed to the ~200 it used to be), I don't think Retina counts as "can't reasonably take input in decimal". Sep 11, 2016 at 12:41
• Ah, I see. I've only ever seen unary input in Retina, thus my confusion. Sep 11, 2016 at 12:45

# Jelly, 9 8 bytes

’ÆRṪạµ¡Ḃ


### How it works

’ÆRṪạµ¡Ḃ  Main link. Argument: n

µ    Combine all atoms to the left into a chain.
’           Decrement; yield n - 1.
ÆR         Prime range; yield all primes in [2, ..., n -1].
Ṫ        Tail; yield p, the last prime in the range.
If the range is empty, this yields p = 0.
ạ       Compute the absolute difference of p and n.
¡   Call the chain to the left n times.
This suffices since each iteration decreases n, until one of the fixed
points (1 or 2) is reached.
Ḃ  Bit; return the parity of the fixed point.


# Regex (ECMAScript or better), 33 32 bytes

^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$ Takes its input in unary, as a string of x characters whose length represents the number. Try it online! - ECMAScript Try it online! - Java Try it online! - Perl Try it online! - PCRE Try it online! - Boost Try it online! - Python Try it online! - Ruby Try it online! - .NET I finally found a use for the positive lookahead primality test I came up with on 2018-12-07! This is 2 bytes longer than the "standard" negative lookahead primality test, but it allows the full regex to be 1 byte shorter: ^ # tail = input number ( # Loop the following: (?= # Atomic lookahead - finds the first match, and once # finished, its result won't be changed by backtracking .+? # tail = largest number that is less than the current tail, # for which the following matches: (?=(xx+?)\2*$)\2$# Assert tail is prime; \2 = tail ) \2 # tail -= \2 )* # Iterate the above loop zero or more times x$                          # Assert tail==1


A neat thing about this regex is that it can be logically negated for all inputs other than zero simply by adding one byte, because after the repeated subtraction, all $$\n>0\$$ end up at either $$\1\$$ or $$\2\$$:

^((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$ Try it online! - ECMAScript Try it online! - Java Try it online! - Perl Try it online! - PCRE Try it online! - Boost Try it online! - Python Try it online! - Ruby Try it online! - .NET Here is the regex implemented in some languages that have golf-efficient regex calls, where it either beats the other submitted solution(s) or is the only one in that language: ### $$\\large\textit{Anonymous functions}\$$ # Julia v0.4+, 58 bytes n->split("x"^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$")[1]==""


Try it online!

The above returns truthy for an input of 0. If returning falsey for 0 were needed, it'd be 60 bytes:

n->match(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$","x"^n)!=nothing  Try it online! or 59 bytes in Julia v0.7 and earlier with !=Void(): Try it online! Of course as far as Julia v0.4 goes, Glen O's answer outgolfs this at 32 bytes, but for v0.5 and later, this and the below may be optimal golf. # Julia v0.7+, 54 bytes n->occursin(r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$",'x'^n)


Try it online!

# Julia v1.2+, 53 bytes

n->endswith('x'^n,r"^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x")


Attempt This Online!

# PowerShell, 52 51 bytes

'x'*"$args"-match'^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$'


Try it online!

-1 bytes thanks to Julian

lambda n:re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n);import re  Try it online! # Python, 73 bytes lambda n:__import__('re').match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*n)


Try it online!

(If it must be a pure lambda.)

n=>/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/.test(Array(n+1))  Try it online! -4 bytes thanks to a technique used by RK. and CubeyTheCube # Perl, 49 47 bytes -2 bytes thanks to dingledooper sub{1x pop~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/}


Try it online!

This beats a port of Ton Hospel's 41 byte answer (57 bytes):

sub{my$x=1x pop;$x=$while$x=~/\B(?!(11+)\1+$|$)|11$/;$x}


Try it online!

Even if it's allowed to modified the global variable $_ (51 bytes): sub{$_=1x pop;$_=$while/\B(?!(11+)\1+$|$)|11$/;$_}


Try it online!

->n{?x*n=~/^((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$/}  Try it online! -2 bytes by switching the truthy value from "string of x characters whose length is the input number" to "the integer value 0", while keeping the same falsey value of nil -1 byte by using ?x instead of "x" # PHP, 8975 71 bytes fn($n)=>preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$n))


Try it online!

-4 bytes by switching from x to   as the repeated character

\(n)grepl('^((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.$',strrep(1,n),,1)  \(n)grepl('^((?=.+?(?!(..+)\\2+$)(..+))\\3)*.$',strrep(1,n),,1)  -1 byte thanks to Giuseppe -4 bytes by using grepl() instead of sum(grep()) or any(grep()) -5 bytes by using a new anonymous function syntax introduced in R v4.1.0 Since TIO uses R v3.5.2, the TIO links have the old 68 byte versions of the function. # Java 8, 928988 71 bytes n->new String(new char[n]).matches("((?=.+?(?=(..+?)\\2*$)\\2$)\\2)*.")  Try it online! n->new String(new char[n]).matches("((?=.+?(?!(..+)\\2+$)(..+))\\3)*.")


Try it online!

-17 bytes by just matching the regex straight against a string of NUL characters instead of replacing the NULs with x

# Java 11, 61 bytes

n->"x".repeat(n).matches("((?=.+?(?=(xx+?)\\2*$)\\2$)\\2)*x")


Try it online!

-10 bytes relative to Java <11, thanks to Kevin Cruijssen

# Python 2, 69 bytes

import re
re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()).re  Outputs via its exit code, value 0 for truthy (by exiting normally), and 1 for falsey (by triggering an AttributeError). Try it online! # Python 2, 71 70 bytes import re re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*input()).re


Outputs via its exit code, value 1 for truthy and 0 for falsey, using the truth-inverted regex.

Try it online!

Alternative method using the uninverted regex, outputting exit code 1 for truthy (by triggering a NameError), and 0 for falsey (by exiting normally), at 71 bytes:

import re
if re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input()):z  Try it online! # Python 2, 79 74 bytes import re print re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*input())>0


Outputs True or False via stdout.

Try it online!

# Python 3, 84 83 bytes

import re
print(not re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*xx$','x'*int(input())))  Try it online! The above uses the truth-inverted regex. Without it is 84 bytes: import re print(bool(re.match(r'((?=.+?(?=(xx+?)\2*$)\2$)\2)*x$','x'*int(input()))))


Try it online!

# PHP-F, 70 bytes

<?=preg_match('/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/',str_pad('',$argn));


Try it online!

# Perl-p, 45 43 bytes

-2 bytes thanks to dingledooper

$_=1x$_~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/  Try it online! Beaten by Ton Hospel's 41 byte answer which mixes regex and code: Try it online! # Perl, 46 44 bytes say 1x<>~~/^((?=.+?(?=(..+?)\2*$)\2$)\2)*.$/


Try it online!

Now beats a port of Ton Hospel's answer (45 bytes):

$_=1x<>;$_=$while/\B(?!(11+)\1+$|$)|11$/;say


Try it online!

• Amazing that these are the shortest answers here for many of these languages, even with the function definition and regex match overhead, etc. Jul 3 at 12:46
• One character shorter in PowerShell Jul 19 at 23:13

# Pyth, 1815 14 bytes

Thanks to @Maltysen for -1 byte

#=-QefP_TUQ)q1


A program that takes input on STDIN and prints True or False as appropriate.

Try it online

How it works

#=-QefP_TUQ)q1  Program. Input: Q
#          )    Loop until error statement (which occurs when Q<3):
UQ      Yield [0, 1, 2, 3, ..., Q-1]
fP_T        Filter that by primality
e            Yield the last element of that
=-Q             Q = Q - that
q1  Q is 1 (implicit variable fill)
Implicitly print


Old version with reduce, 18 bytes

qu-G*<HGH_fP_TSQQ1


Try it online

How it works

qu-G*<HGH_fP_TSQQ1  Program. Input: Q
SQ    Yield [1, 2, 3, ..., Q]
fP_T      Filter that by primality
_          Reverse it
u                  Reduce it:
Q    with base case Q and
function G, H ->
<HG              H<G
*   H             *H (yields H if H<G, else 0)
-G                  Subtract that from G
q                1  The result of that is 1
Implicitly print

• St is U 15 chars Sep 11, 2016 at 18:45
• 13 bytes Mar 29, 2021 at 22:32

# JavaScript (ES6), 64 63 bytes

Saved 1 byte thanks to @Neil

g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))


I wrote this in 2 minutes... and it worked perfectly the first time. First user to find the inevitable bug wins....

### Try it out

g=(x,n=x-1)=>n<2?x:x%n?g(x,n-1):g(x-1)
f=x=>x<3?x%2:f(x-g(x-1))
<input type="number" value=3 min=3 onchange="A.innerHTML=f(this.value)"><br>
<p id=A>1</p>

### How it works

First we define g(x) as the function that finds the first prime number p <= x. This is done using the following process:

2. If n < 2, x is prime; return x.
3. If x is divisible by n, decrement x and go to step 1.
4. Otherwise, decrement n and go to step 2.

The solution to this challenge, f(x), is now fairly straightforward:

1. If x < 3, return x = 1.
2. Otherwise, subtract g(x-1) and try again.
• 4326, which should return true does not seem to return, but 4328 (true) and 4329 (false) do, is this a JS limitation or a bug? Sep 11, 2016 at 20:34
• @JonathanAllan 4326 throws too much recursion to the browser console in Firefox 48, so I guess the recursion passes FF's recursion limit. Sep 11, 2016 at 20:38
• Yep, next prime down is 4297 (and next up is 4327), which will be why 4328 works. Sep 11, 2016 at 20:44
• x%2 should save you a byte over x==1.
– Neil
Sep 11, 2016 at 23:52
• @Neil I would never have thought of that :-) Sep 12, 2016 at 13:56

# Julia (0.4), 32 bytes

(Update (as of 1.4): This is rather out-of-date, now - primes is no longer in Base, and ?: needs spaces around the ? and the :)

While it's not going to be the shortest solution among the languages, this might be the shortest of the human-readable ones...

!n=n>2?!(n-primes(n-1)[end]):n<2


Try it online!

Or, to put it in slightly clearer terms

function !(n)
if n>2
m=primes(n-1)[end]   # Gets largest prime less than n
return !(n-m)        # Recurses
else
return n<2           # Gives true if n is 1 and false if n is 2
end
end


Called with, for example, !37.

## Pyke, 15 11 bytes

WDU#_P)e-Dt


Try it here!

            - stack = input
W           - while continue:
U#_P)     -     filter(is_prime, range(stack))
e    -    ^[-1]
D      -   -   stack-^
Dt -  continue = ^ != 1


Returns 1 if true and raises an exception if false

# Husk, 11 9 bytes

εωλ-→fṗŀ¹


Try it online!

-2 bytes from Leo.

None of the testcases reach zero because the max number we can subtract from n can only be n-1. Hence, we can check insignificance instead of equality with 1.

## Explanation

εωλ-→fṗŀ¹
ωλ       iterate on the input till fixpoint
ŀ¹  range 0..n-1
fṗ    filter out nonprimes
→      last element
-       subtract from n
ε         is fixed point insignificant? (<= 1?)

• Can be shortened by iterating until fixed point: Try it online!
– Leo
Apr 6, 2021 at 0:47

# Python3, 102 92 90 89 88 bytes

f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])


Golfing suggestions welcome! I see that gmpy contains a function next_prime, but I can't test it yet :(

-2 bytes, thanks to @JonathanAllan!

-1 byte, thanks to @Aaron!

## Testcases

f=lambda n:n<2if n<3else f(n-[x for x in range(2,n)if all(x%y for y in range(2,x))][-1])

s="3 4 6 8 10 11 12 14 16 17 18 20 22"
h="5 7 9 13 15 19 21 25 28 31 33 36 39"

for j in s.split(" "):print(f(int(j)))
for j in h.split(" "):print(f(int(j)))


Output is 13 truthy values and 13 falsey values. s contains the truthy cases and h the falseys.

• if all(x%y for... works Sep 11, 2016 at 18:00
• n<3 else -> n<3else to get same length as mine ;) Sep 13, 2016 at 16:20

f n|n>2=f$n-last[p|p<-[2..n-1],all((>0).mod p)[2..p-1]]|1>0=n<2  Try it online! ## Mathematica, 32 bytes 2>(#//.x_/;x>2:>x+NextPrime@-x)&  This is an unnamed function which takes an integer and returns a boolean. ### Explanation There's a lot of syntax and funny reading order here, so...  # This is simply the argument of the function. //. This is the 'ReplaceRepeated' operator, which applies a substitution until the its left-hand argument stops changing. x_/;x>2 The substitution pattern. Matches any expression x as long as that expression is greater than 2. :> Replace that with... NextPrime@-x Mathematica has a NextPrime built-in but no PreviousPrime built-in. Conveniently, NextPrime works with negative inputs and then gives you the next "negative prime" which is basically a PreviousPrime function (just with an added minus sign). x+ This gets added to x, which subtracts the previous prime from it. 2>( ) Finally, we check whether the result is less than 2.  • Closely beats #+0~Min~NextPrime@-#&~FixedPoint~#==1& (36 bytes). Nice use of //. ! Sep 11, 2016 at 20:31 • @GregMartin 35 when you use <2 at the end. Sep 11, 2016 at 20:54 # Python, with sympy, 60 bytes import sympy f=lambda n:n>2and f(n-sympy.prevprime(n))or n<2  My previous method was 83 bytes without sympy using recursion, but I took truthy/falsey to mean distinguishable and consistent, but I have been informed that's an incorrect interpretation. I can't seem to salvage it due to the tail, but I'll leave it here in case someone knows how to do so: f=lambda n,p=0:n>2and(any(p%x==0for x in range(2,p))and f(n,p-1)or f(n-p,n+~p))or n  • 2 is not a falsey value. Sep 12, 2016 at 13:45 • @mbomb007 I thought specs are "true or false" if that is required, whereas "truthy or falsey" means distinguishable and consistent? Sep 12, 2016 at 21:01 • Nope. They are defined as we decided on the meta site. Any question that allows "distinguishable and consistent" output must specify that, rather than truthy/falsey. Sep 12, 2016 at 21:04 • OK I read this, will update at some point... Sep 12, 2016 at 21:20 # APL (Dyalog Unicode), 27 bytes {⍵<3:⍵=1⋄∇⍵-⊃⌽(⊢~∘.×⍨)2↓⍳⍵} ⍵<3 ⍝ Termination condition :⍵=1 ⍝ return value ⋄ ⍝ Separator ∇ ⍝ Recursive call ⍵-⊃⌽ ⍝ Subtract largest prime (⊢~∘.×⍨) ⍝ Calculate primes less than argument 2↓⍳⍵ ⍝ Range 2–(N-1)  Try it online! # Brachylog, 11 bytes 1|-↙Xṗ∧X≜!↰  Try it online! 1 The input is 1, | or: X≜ X is the integer with the least absolute value such that -↙X it is positive, and if it is subtracted from the input ṗ∧ the result is prime. ! Consider no other value of X. ↰ Call this predicate again with X as the input.  # Vyxal, 7 bytes ‡∆ṗεẊ1=  Try it Online! Very nice and neat answer (flagless too!) ## Explained ‡∆ṗεẊ1= ‡∆ṗε # lambda x: abs(x - prev_prime(x)) Ẋ # repeat that on the input until it doesn't change 1= # does that equal 1?  • What's even more surprising is that this still works. You can save a byte with either ∷ or ₂ instead of 1= Jun 18 at 20:59 # MATL, 13 bytes tqZq0)-t2>}o  ### Explanation  % Do...while t % Duplicate. Takes input implicitly in the first iteration qZq % All primes less than that 0) % Get last one - % Subtract (this result will be used in the next iteration, if any) t % Duplicate 2> % Does it exceed 2? If so: next iteration. Else: execute the "finally" % block and exit do...while loop } % Finally o % Parity. Transforms 2 into 0 and 1 into 1 % End do...while implicitly % Display implicitly  # CJam, 21 16 bytes Thanks to Dennis for saving 4 bytes. ri{_1|{mp},W=-}h  Try it online! ### Explanation ri e# Read input and convert to integer N. { e# Run this block as long as N is positive (or until the program aborts e# with an error)... _1| e# Duplicate and OR 1. This rounds up to an odd number. For N > 2, this e# will never affect the greatest prime less than N. {mp}, e# Get all primes from 0 to (N|1)-1. e# For N > 2, this will contain all primes less than N. e# For N = 2, this will contain only 2. e# For N = 1, this will be empty. W= e# Select the last element (largest prime up to (N|1)-1). e# For N = 1, this will result in an error and terminate the program, which e# still prints the stack contents though (which are 1, the desired output). - e# Subtract from N. Note that this gives us 0 for N = 2, which terminates the e# loop. }h  • ri_{_1|{mp},W=-}* should work. Sep 11, 2016 at 19:01 • @Dennis Thanks, the 1| is really clever. :) (And I always forget that {...}, does an implicit range...) Sep 11, 2016 at 21:00 # Perl, 42 bytes Includes +1 for -p Run with input on STDIN reach1.pl: #!/usr/bin/perl -p$_=1x$_;$_=$while/\B(?!(11+)\1+$|$)|11$/


Uses the classic primality regex

## .NET Regex, 38 bytes

Just to show that it can be checked in a single regex.

^(?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+.$


Input is assumed to be in unary.

### Explanation

It simply implements the requirement to the word, repeatedly removing the biggest prime and check whether there remainder is 1.

• (?>(?<=(.*))..+(?<!^\1\2+(.+.)|$))+: Non-backtracking group makes sure the biggest prime we found is not overriden, and + simply repeat the process of matching the biggest prime. • (?<=(.*))..+(?<!^\1\2+(.+.)|$): Match the biggest prime less than the remaining number

• (?<=(.*)): Record how much we have subtracted to establish an "anchor" point for assertion.

• ..+: Look for the biggest number...

• (?<!^\1\2+(.+.)|$): ... which is prime and less than the remaining number. • (?<!^\1\2+(.+.)): The usual prime test routine, with ^\1 tacked in front to make sure we are checking the amount matched by ..+ • (?!<$): Assert less than the remaining number
• The (?<=(.*)) part is rather clumsy. Not sure if there is a better way. Also, I'm curious if there is a solution in PCRE. Sep 13, 2016 at 10:50
• What in the.... Sep 8, 2020 at 10:55
• I think this is a case of when you have a hammer (lookbehind), every problem looks like a nail :-) I've been guilty of the same. But it can be done in 32 bytes in any engine supporting positive lookahead. Mar 21, 2021 at 19:28

# Python 2.7: 88 87 Bytes

r=lambda n:n>2and r(n-[a for a in range(2,n)if all(a%b for b in range(2,a))][-1])or n<2


Thx @TuukkaX for -1 more byte!

• Update your description ;) Also, you could save one byte by saying n<2 instead of n==1. Sep 14, 2016 at 9:37
• Try it online! Apr 5, 2021 at 5:34
• 86 bytes Jul 19 at 22:29

# Factor + math.primes, 51 bytes

[ [ dup 1 - primes-upto last - dup 2 > ] loop 1 = ]


Try it online!

# Vitsy, 28 26 bytes

This can definitely be shortened.

<]xN0)l1)-1[)/3D-];(pD-1[D


<                    Traverse the code in this direction, rotating on the line.
For the sake of reading the code easier, I'm reversing the
code on this line. This will be the order executed.

D[1-Dp(;]-D3/)[1-)1l)0Nx]
D                         Duplicate the top member of the stack.
[      ]                 Do the stuff in brackets until break is called.
1-                      Subtract 1 from the top item of the stack.
D                     Duplicate the top member of the stack.
p(                   If the top member is a prime...
;                  break;
-                Pop a, b, push a - b.
D3/)[         ] If this value is less than 3, do the bracketed code.
1-         Subtract the top item of the stack by 1.
)        If the top item is zero...
1       Push 1.
l)     If the length of the stack is zero...
0    Push 0.
N   Output the top member of the stack.
x  System.exit(0);


Try it online!

# Perl 6,  54 53 52  51 bytes

{($_,{$_-($_-1...2).first: *.is-prime}...3>*)[*-1]==1} {($_,{$_-($_-1...2).first: *.is-prime}...3>*).any==1}
{any($_,{$_-($_-1...2).first: *.is-prime}...3>*)==1}  {any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}


## Explanation:

# bare block lambda with implicit parameter ｢$_｣ # used to generate all of the rest of the elements of the sequence { # create an any Junction of the following list any($_, # initialize sequence with the inner block's argument

# bare block lambda with implicit parameter ｢$_｣ { # take this inner block's argument and subtract$_ -

( ^$_ ) # Range up-to and excluding ｢$_｣
.grep(*.is-prime)\ # find the primes
[ * - 1 ]          # return the last value
}

...   # keep doing that until

3 > * # the result is less than 3

# test that Junction against ｢1｣
# ( returns an ｢any｣ Junction like ｢any(False, False, True)｣ )
) == 1
}


## Example:

# show what is returned and if it is truthy
sub show ($_) { # ｢.&{…}｣ uses the block as a method and implicitly against ｢$_｣
my $value = .&{any($_,{$_-(^$_).grep(*.is-prime)[*-1]}...3>*)==1}
say join "\t", $_, ?$value, $value.gist; } show 3; # 3 True any(False, True) show 4; # 4 True any(False, True) show 5; # 5 False any(False, False) show 10; # 10 True any(False, False, True) show 28; # 28 False any(False, False, False) show 49; # 49 False any(False, False) show 50; # 50 True any(False, False, True)  # Irregular, 63 bytes p~?1_$-1p:;
n=i(0)?1_$-1p:; _~ N=n 1(?!(11+)\1+$)11+~1
^11$~0 N  I created this language two days ago, and the basic premises are that there are no built in loops, the only features are basic arithmetic and decision making, and program evaluation is based on regular expressions. ## Explanation p~?1_$-1p:;
n=i(0)?1_$-1p:; _~ N=n  This part converts the input into unary. It repeatedly subtracts 1 from the input until it equals 0, prepending 1_ each time. It then removes all of the _s. If I hadn't forgotten a break in my code it could be written as so: p~?1_$-1p:;
_~
n=i(0)?1_$-1p:;  The next part repeatedly removes the largest prime from the input until it is equal to 1 or 11, with 11 being replaced with 0. 1(?!(11+)\1+$)11+~1
^11$~0 N  I used the regex from Martin Ender's answer. ## PowerShell v2+, 81 bytes param($n)while($n-gt2){$n-=(($n-1)..2|?{'1'*$_-match'^(?!(..+)\1+$)..'})[0]}!--$n


Takes input $n. Enters a while loop so long as $n is still 3 or greater. Each iteration, subtracts a number from $n. The number is the results of the regex primality test applied against a range ($n-1)..2 via the Where-Object (?) operator, then the first [0] of the results (since the range is decreasing, this results in the largest one being selected). After concluding the loop, $n is either going to be 1 or 2, by definition, so we pre-decrement $n (turning it into either 0 or 1), and take the Boolean-not ! thereof. That's left on the pipeline and output is implicit.

### Examples

PS C:\Tools\Scripts\golfing> 3..20|%{"$_ --> "+(.\can-the-number-reach-one.ps1$_)}
3 --> True
4 --> True
5 --> False
6 --> True
7 --> False
8 --> True
9 --> False
10 --> True
11 --> True
12 --> True
13 --> False
14 --> True
15 --> False
16 --> True
17 --> True
18 --> True
19 --> False
20 --> True


# Floroid, 45 30 29 bytes

f=Bb:b<2Fb<3Gf(b-en(b-1)[-1])


# Clojure, 125 bytes

#(loop[x %](if(> x 2)(recur(- x(loop[y(dec x)](if(some zero?(vec(for[z(range 2 y)](mod y z))))(recur(dec y))y))))(quot 1 x)))


Yikes, that is one long piece of code. The most verbose language strikes again!

Ungolfed:

(defn subprime [n]
(loop [x n]
(if (> x 2)
(recur
(- x
(loop [y (dec x)]
(if (some zero? (vec (for [z (range 2 y)] (mod y z))))
(recur (dec y)) y))))
(quot 1 x))))


# 05AB1E, 7 bytes

ΔD<ÅPà-


Outputs 2 as falsey (only 1 is truthy in 05AB1E).

Explanation:

Unfortunately the previous prime builtin ÅM goes into an infinite loop for $$\\leq2\$$, otherwise it could have been used to save a few bytes.

Δ        # Loop until the result no longer changes:
D       #  Duplicate the current value
#  (which is the implicit input-integer in the first iteration)
<ÅP    #  Pop it, and push a list of all primes < this value:
<      #   Decrease the value by 1
ÅP    #   Pop and push a list of all primes <= this value-1
à   #  Pop and push the maximum prime of this list
#  (or an empty string if the list is empty)
-  #  Subtract it from the value (where subtracting the empty string is a no-op)
# (after which the found result is output implicitly)

• Ooh, very convenient for this challenge that 05AB1E's booleans work that way. Jul 26 at 16:22
• @Deadcode Yep, sometimes it can be useful that only 1 is truthy in 05AB1E. Not just with outputs, but also with filters and such. :) But if a 1/0 was expected as result, it would only cost 2 bytes: } to close the loop, and Θ, the 05AB1E-style truthify (basically an ==1 check, returning 0 for everything else). Jul 26 at 17:38

(<2).until(<3)(until(flip(until(+1))2.(.)(<1).mod>>=(==))pred.pred>>=flip(-))

v=@(x)x-max(primes(x-1));while(x>=3)x=v(x);end;x==1