Does the code terminate?

95

13

This is a code golf challenge I thought of with a mathematical bent. The challenge is to write the shortest code possible such that it is an open question whether or not the code terminates. An example of what I mean could be the following piece of python code, adapted from an anwser to this cs stackexchange question.

def is_perfect(n):
    return sum(i for i in range(1, n) if n % i == 0) == n

n = 3
while not is_perfect(n):
    n = n + 2

Mathematicians conjecture that there are no odd perfect numbers, but it has never been proven, so no one knows if this piece of code will ever terminate. Can you come up with other pieces of code (perhaps relying on other open problems like the Collatz conjecture, or the twin primes conjecture) that are shorter, but for which it is unknown whether or not they terminate?

Edit: Some people have brought up a good additional rule - The solutions to the question should be deterministic. Although it might be even more interesting if you could find shorter solutions using nondeterminism. In this case, the rule would be to find a snippet for which the probability of termination is unknown.

Bolton Bailey

Posted 2016-10-21T23:02:55.273

Reputation: 947

2Welcome to PPCG! – Luis Mendo – 2016-10-22T00:03:08.787

3Your code can be golfed to 50 bytes: n=3 while sum(k*(n%k<1)for k in range(1,n))-n:n+=2. – xnor – 2016-10-22T01:24:43.240

14This really is a great concept. It's nice to see original ideas like this. – Nathan Merrill – 2016-10-22T01:59:34.867

And here I thought this was going to be related to the Church-Turing thesis Nice question!

– MayorMonty – 2016-10-22T02:18:20.440

1Useful – Post Rock Garf Hunter – 2016-10-22T05:23:09.407

May we assume infinite memory? – Mego – 2016-10-22T08:15:02.170

7@Mego I think this challenge only works if you assume infinite data types what will automatically assume infinite memory. – Martin Rosenau – 2016-10-22T09:41:46.917

54When I read the title I thought you wanted us to solve the halting problem AND golf the solution. – MrPaulch – 2016-10-22T12:00:35.617

1Are snippets explicitly allowed, or is it only full programs or functions? – Buffer Over Read – 2016-10-24T15:46:17.337

I love this challenge, because it's basically asking users to solve open-ended problems, which the world wants solved anyway. – mbomb007 – 2016-10-24T18:31:21.143

1

@WheatWizard I used this much longer list on Wikipedia.

– mbomb007 – 2016-10-24T18:32:49.503

It is an open problem how long before cosmic rays trigger an infinite loop to NMI reset. – Joshua – 2016-10-24T19:55:48.340

This reminds me of the paper A Relatively Small Turing Machine Whose Behavior Is Independent of Set Theory, which details a Turing machine that runs forever but cannot be proven to do so using the axioms of ZFC set theory. (The paper even likens the construction of the Turing machine to "code-golfing.")

– 2012rcampion – 2016-10-25T03:13:35.407

I think this should be closed: As soon as one of the used conjectures is proven, people have to delete their answers. And it is not too difficult to come up with own conjectures, that might have trivial answers. – flawr – 2016-10-25T09:30:03.377

We have already closed essentially this same question twice, IIRC. It has two major problems: 1. "Open question" under what assumptions? There are programs which are known to terminate if you assume some extremely strong axioms, but unknown otherwise. 2. It's a multi-duplicate of existing questions relating to Goldbach, Collatz, etc.

– Peter Taylor – 2016-10-26T14:38:32.410

Is "Will you let this program run continuously for 10 years?" an open problem? – 12Me21 – 2018-12-30T17:48:46.287

Answers

29

Jelly, 7 bytes

!‘Ʋµ4#

Try it online!

Background

This will terminate once it finds a fourth solution to Brocard's problem, i.e. a solution n! + 1 = m² with (n,m) ≠ (4, 5), (5, 11), (7, 71) over the positive integers. The implementation doesn't use floating point arithmetic, so it will only terminate if it does find a fourth solution or if n! can no longer be represented in memory.

Brocard's problem was first used in this answer by @xnor.

How it works

!‘Ʋµ4#  Main link. No arguments. Implicit argument: 0

    µ4#  Convert the links to the left into a monadic chain and call it with
         arguments k = 0, 1, 2, ... until 4 of them return 1.
!        Factorial; yield k!.
 ‘       Increment; yield k! + 1.
  Ʋ     Squareness; return 1 if k! + 1 is a perfect square, 0 if not.

Dennis

Posted 2016-10-21T23:02:55.273

Reputation: 196 637

3I need to learn jelly... – noɥʇʎԀʎzɐɹƆ – 2016-10-23T19:42:45.443

19

Jelly, 11 9 bytes

ÆẸ⁺‘ÆPµ6#

This will terminate once the sixth Fermat prime is found.

Try it online!

How it works

ÆẸ⁺‘ÆPµ6#  Main link. No arguments. Implicit argument: 0

      µ6#  Convert the links to the left into a monadic chain and call it with
           arguments k = 0, 1, 2, ... until 6 of them return 1.
ÆẸ         Convert [k] to the integer with that prime exponent factorization, i.e.,
           into 2 ** k.
  ⁺        Repeat.
   ‘       Increment.
           We've now calculated 2 ** 2 ** k + 1.
    ÆP     Test the result for primality.

Dennis

Posted 2016-10-21T23:02:55.273

Reputation: 196 637

16

Pyth, 10 bytes

fP_h^2^2T5

Uses the conjecture that all Fermat numbers 2^(2^n)+1 are composite for n>4.

f        5   Find the first number T>=5 for which
   h^2^2T    2^(2^T)+1
 P_          is prime                   

xnor

Posted 2016-10-21T23:02:55.273

Reputation: 115 687

11

Perl, 50 38 36 34 33 bytes

$_=196;$_+=$%while($%=reverse)-$_

Explanation: 196 is a possible Lychrel number - a number that does not form a palindrome by repeatedly adding its reverse to itself. The loop continues until $n is equal to its reverse, which is as yet unknown for initial value 196.

25 + 52 = 77

which is not valid.

96 + 69 = 165
165 + 561 = 726
726 + 627 = 1353
1353 + 3531 = 4884

so none of the numbers in this sequence are valid.

Edit: Golfed it down by using an until loop instead of a for loop (somehow). Also, I had fewer bytes than I thought (I should probably look at my bytecount more carefully in the future).

Edit: Replaced $n with $_ to save 2 bytes for the implied argument in reverse. I think this is as golfed as this implementation is going to get.

Edit: I was wrong. Instead of using until($%=reverse)==$_ I can go while the difference is nonzero (i.e. true): while($%=reverse)-$_.

Gabriel Benamy

Posted 2016-10-21T23:02:55.273

Reputation: 2 827

3Since there are a finite number of possible plain perl numbers I can in fact determine if this program terminates or not. You need to load a bigint package to make this work (or implement it) – Ton Hospel – 2016-10-22T08:09:06.930

Do it. I dare you. :-) – Veky – 2016-10-23T21:26:17.270

11

MATL, 11 bytes

`@QEtZq&+=z

Terminates iff the Goldbach conjecture is false. That is, the program stops if it finds an even number greater than 2 that cannot be expressed as the sum of two primes.

`        % Do...while
  @      %   Push iteration index k. Gives 1, 2, 3, ...
  QE     %   Add 1 and multiply by 2. Gives 4, 6, 8, ...
  tZq    %   Duplicate. Push all primes up to current k
  &+     %   Matrix with all pairwise additions of those primes
  =z     %   Number of entries of that matrix that equal k. This is used as loop
         %   condition. That is, the loop continues if this number is nonzero
         % Implicit end

Luis Mendo

Posted 2016-10-21T23:02:55.273

Reputation: 87 464

11

Python, 36 bytes

k=n=1
while(n+1)**.5%1+7/k:k+=1;n*=k

Uses Brocard's problem:

Is n!+1 a perfect square for any n≥8?

Computes successive factorials and checks whether they are squares and have k>7. Thanks to Dennis for 2 bytes!

This assumes Python continues to have accurate arithmetic for arbitrarily large numbers. In actual implementation, it terminates.

xnor

Posted 2016-10-21T23:02:55.273

Reputation: 115 687

1Would -~n**.5 not work in place of (n+1)**.5? – ETHproductions – 2016-10-22T15:59:34.923

@ETHproductions The precedence of exponentation is higher than the precedence of ~, so that would just raise a TypeError for trying to negate a float bitwise. – Dennis – 2016-10-22T21:22:34.297

8

05AB1E, 8 bytes

Will terminate when the 6th Fermat prime is found.

5µNoo>p½

Explanation

5µ          # loop over increasing N (starting at 1) until counter reaches 5
  Noo       # 2^2^N
     >      # + 1
      p½    # if prime, increase counter

Emigna

Posted 2016-10-21T23:02:55.273

Reputation: 50 798

8

Python, 30 28 bytes

n=2
while 2**~-n%n**3-1:n+=1

This program will halt if and only if there is an integer n bigger than 1 such that 2^(n-1)-1 is divisible by n^3. To my knowledge it is not known whether any number with this property exists (if a number satisfying this property is prime, it is called a Wieferich prime of order 3 to base 2, and it is open whether any such prime exists).

Julian Rosen

Posted 2016-10-21T23:02:55.273

Reputation: 181

Are you sure the parentheses are placed correctly? It looks like you're testing to see if 2^(n-1) !≡ 1 (mod n^3), not 2^n ≡ 1 (mod n^3). Granted, I don't know Python's operator precedence all that well. – Gabriel Benamy – 2016-10-24T18:51:26.773

Whoops, the code is correct, but my explanation isn't. I'll fix it. – Julian Rosen – 2016-10-24T18:53:08.440

2you can replace (n-1) with ~-n – Post Rock Garf Hunter – 2016-10-24T18:59:53.707

2**n%n**3-2 is shorter – H.PWiz – 2019-12-15T15:26:17.990

7

Brachylog (v2), 3 bytes in Brachylog's encoding

⟦cṗ

Try it online! (will time out without doing anything visible, for obvious reasons)

Full program; if run with no input, searches for the first Smarandache prime, and outputs true. if and when it finds one. It's an open question as to whether any Smarandache primes exist. (Note that Brachylog's prime-testing algorithm, although it works in theory on arbitrarily large numbers, tends to run slowly on them; thus, if you're interested in finding Smarandache primes yourself, I recommend using a different language.)

Explanation

⟦cṗ
⟦     Form an increasing range from 0 to {the smallest number with no assertion failure} 
 c    Concatenate all the numbers that make up that range, in decimal
  ṗ   Assert that the result is prime

Brachylog operates on the decimal digits of a number whenever you try to treat it like a list, so "range" followed by "concatenate" is a very terse way to generate the sequence of Smarandache numbers (and then we filter that by primality; Brachylog's default full program behaviour will then force the first element of the resulting generator). The range has a leading zero, but fortunately, with this flow pattern, Brachylog removes the zero rather than failing.

Here's an example that finds the first Smarandache number that's equal to 6 (mod 11), as a demonstration of a similar program that terminates within 60 seconds rather than having unknown halting status:

⟦c{-₆~×₁₁&}

Try it online!

This would print true. as a full program, but I threw in the Z command line argument to actually print the number in question, giving a better demonstration that this general approach works.

ais523

Posted 2016-10-21T23:02:55.273

Reputation: 11

7

Haskell, 47 bytes

[n|n<-[1..],2*n==sum[d|d<-[2..n],n`mod`d<1]]!!0

Searching the first quasiperfect number, which is a number n whose sum of divisors is 2*n+1. Instead of adding 1, I exclude 1 from the list of divisors.

Christian Sievers

Posted 2016-10-21T23:02:55.273

Reputation: 6 366

6

Brain-Flak, 212 208 204 bytes

This program uses a multiplication algorithm written by MegaTom and a non-square checker written by 1000000000

Try It Online

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

This program starts at 8 and tests each number to see if n!+1 is a square number. It exits when it finds one. This is known as Brocard's Problem and it is an open problem in mathematics.

Post Rock Garf Hunter

Posted 2016-10-21T23:02:55.273

Reputation: 55 382

5

Python 2, 88 bytes

p=lambda n:all(n%x for x in range(2,n))
s=lambda n:0if p((10223*2**n)+1)else s(n+1)
s(0)

This code will terminate if 10223 is a Sierpiński number. 10223 is currently the smallest candidate that may or may not be a Sierpiński number, as of December 2013.

A Sierpiński number is a number k in which all numbers of the form (k * 2^n) + 1 are composite.

clismique

Posted 2016-10-21T23:02:55.273

Reputation: 6 600

I hope this problem and the Sierpinski problem are resolved in the near future, just with more calculations. – qwr – 2016-10-22T08:05:01.757

4This code surely terminates, since you just name two lambdas, you don't actually call anything. :-P – Veky – 2016-10-23T21:34:36.260

@Veky sigh Fixed... – clismique – 2016-10-25T08:57:51.700

4

In fact you didn't. Your code still always terminates, since Python2 semantics is frozen (PEP 404), and it includes a hard limit on recursive calls by BDFL's fiat (http://neopythonic.blogspot.hr/2009/04/final-words-on-tail-calls.html). ;-P

– Veky – 2016-10-26T04:03:02.640

2@Veky Had to upvote your comment. – clismique – 2016-10-26T04:48:34.560

I also had to upvote yours. It made me laugh. :-D – Veky – 2016-10-26T05:29:42.813

1

Not many days after this was written, the prime 10223*2^31172165 + 1 was discovered. Since then, 21181 has been the smallest number for which it is not known if it is Sierpiński or not.

– Jeppe Stig Nielsen – 2019-05-06T05:00:59.857

4

Pyth, 16 bytes

f!}1.u@,/G2h*3GG

Returns the first value for which the Collatz conjecture does not hold. As it is unknown whether the conjecture holds for all numbers, it is unknown whether this code will terminate.

Steven H.

Posted 2016-10-21T23:02:55.273

Reputation: 2 841

3Without being able to read it, I doubt your code does exactly what you claim. Do you search for the first number that goes to a loop different from 4-2-1? I guess you won't find it if there is a smaller number that doesn't end in any loop. Anyway, if that's what your code does, that's good enough for not knowing whether it will terminate. – Christian Sievers – 2016-10-22T00:35:47.100

1I search for the first integer >= 1 that goes to a loop and nowhere within the traversal to that loop contains a 1. – Steven H. – 2016-10-22T02:00:41.583

3That's what I expected. But that's not the only conceivable way for a number to not satisfy the collatz conjecture. – Christian Sievers – 2016-10-22T02:11:02.170

Actually, it has been proven that every number either diverges to infinity or coverges to 1-2-4 under the Collatz map. Your code will never terminate. The idea is that the sequence of steps that forms a loop sets up an equation, whose only solutions are 1-2-4, negative values and non-integer rationals. – John Dvorak – 2016-10-22T12:48:54.083

3@JanDvorak I do not believe that is true. Can you cite a source? – KSFT – 2016-10-22T17:03:41.943

@ksft I did not manage to find the proof I remember from years ago, unfortunately. I did find this MO question from 2011 regarding the topic, though: http://mathoverflow.net/questions/68751/larger-cycle-than-4-2-1-in-collatz-iteration. It does trim the cycle space quite significantly. The same result is quoted on Wikipedia. I'll consider this answer valid for now but I'll also keep it in tabs in case I do find the proof I saw and I'm not mis-remembering things.

– John Dvorak – 2016-10-23T10:20:11.253

4

Actually, 16 bytes

1`;;pY)▒@D÷íu*`╓

Try it online!

This code terminates iff there is some composite number n such that totient(n) divides n-1 (Lehmer's totient problem).

Explanation:

1`;;pY)▒@D÷íu*`╓
1`            `╓  first integer, starting with 0, where the following function leaves a truthy value on top of the stack:
    pY       *      composite (not prime) and
   ;  )▒            totient(n)
  ;     @D֒u       is in the list of divisors of n-1

Mego

Posted 2016-10-21T23:02:55.273

Reputation: 32 998

4

Jelly, 9 8 bytes

-1 byte thanks to @Dennis! (use exponentiation instead of multiplication to avoid Æṣ(0))

*ḂÆṣ=µ2#

Will return a list of zero and the smallest odd perfect number, if any exist.

How?

*ḂÆṣ=µ2# - Main link: no arguments
     µ   - monadic chain separation
      2# - count up from implicit `n=0` and return the first 2 truthy results of
 Ḃ       -     mod 2        -> n%2
*        -     exponentiate -> n**(n%2)  (1 when n is even, n when n is odd)
  Æṣ     -     sum of proper divisors of n**(n%2)
    =    -     equals n?    -> 1 if n is zero or both perfect and odd, else 0

Jonathan Allan

Posted 2016-10-21T23:02:55.273

Reputation: 67 804

4

Haskell, 46 bytes

[n|m<-[1..],n<-[1..m],product[1..n]+1==m^2]!!3

Terminates if it finds the 4th solution to brocard's problem.

BlackCap

Posted 2016-10-21T23:02:55.273

Reputation: 3 576

3

Python 2, 123 98 92 bytes

p=lambda n,k=2:n<=k or n%k*p(n,k+1)
g=lambda n:[p(b)*p(n-b)for b in range(n)]and g(n+2)
g(4)

This code will terminate if the Goldbach conjecture does not hold for all even numbers (i.e. if all even numbers can be expressed as the sum of two primes). It has currently been tested for numbers up to 4*10^18.

A huge amount of thanks to @Pietu1998 for shortening my code by a lot!

EDIT: Thanks to @JonathanAllan for shaving 6 bytes off my code!

clismique

Posted 2016-10-21T23:02:55.273

Reputation: 6 600

I think you can save 6 bytes with g=lambda n:[p(b)*p(n-b)for b in range(n)]and g(n+2). I also think this should read "will terminate if the Goldbach conjecture does not hold". – Jonathan Allan – 2016-10-24T00:31:44.290

3

Python, 92 bytes

This isn't winning any code golf competitions, and it requires infinite memory and recursion depth, but this is an almost perfect opportunity to plug an interesting problem I asked on math stackexchange two years ago, that no Fibonacci number greater than 8 is the sum of two positive cubes. Funnily enough, it started as an code golf challenge idea, so I guess I've come full circle.

def f(i,j):
 r=range(i)
 for a in r:
  for b in r:
   if a**3+b**3==i:1/0
 f(j,i+j)
f(13,21)

qwr

Posted 2016-10-21T23:02:55.273

Reputation: 8 929

2

JavaScript (ES6), 104 101 bytes

for(n=[6,9,p=1];!p;n=n.map((x,i)=>(q=n[n.length+~i],p|=x^q,c=q+x+c/10|0)%10).concat(c/10|0||[]))c=p=0

Uses the same method as the Perl answer: sets n to 196, then repeatedly adds n to its base 10 reverse until it's a palindrome in base 10. This would be shorter if JS supported arbitrary-precision numbers, but oh well.

ETHproductions

Posted 2016-10-21T23:02:55.273

Reputation: 47 880

Although this is long, it's cleverly golfed, so +1. – wizzwizz4 – 2016-10-25T09:02:05.217

2

Python, 80 bytes

Terminates if the Collatz Conjecture is proven false. See this question.

n=2
while 1:
 L=[];x=n
 while~-n:1/(n not in L);L+=[n];n=(n/2,n*3+1)[n%2]
 n=x+1

mbomb007

Posted 2016-10-21T23:02:55.273

Reputation: 21 944

That's disgusting, but also beautiful. – James Murphy – 2016-10-29T05:52:17.620

1

Jelly, 7 bytes

*+3Ẓµ4#

Try it online! (prints two elements, not 4, so that you can actually see it halt)

Prints the first four \$n\$ such that \$n^n+3\$ is prime. It is not known whether four+ numbers with this property exist. The first three are 2, 1036, and 2770.

Explanation

*+3Ẓµ4#
     4#  Find the first four numbers with the following property:
    µ      (bracketing/grouping: place everything to the left inside the loop)
*          {The number} to the power of {itself}
 +3        plus 3
   Ẓ       is prime

ais523

Posted 2016-10-21T23:02:55.273

Reputation: 11

1

Python 2, 64 bytes

A Lychrel number is a natural number that cannot form a palindrome through the iterative process of repeatedly reversing its digits and adding the resulting numbers.

No Lychrel numbers have been proven to exist in base ten. 196 is the smallest base ten Lychrel number candidate. It has been shown that if a palindrome exists (making 196 not a Lychrel number), it would have at least a billion (10^9) digits, because people have run the algorithm that long.

n=196
while 1:
    x=str(n);r=x[::-1]
    if x!=r:n=n+int(r)
    else:1/0

mbomb007

Posted 2016-10-21T23:02:55.273

Reputation: 21 944

@trichoplax Ah, the tabs / spaces "feature" strikes again... – wizzwizz4 – 2016-10-25T09:28:13.340

1

If anyone else also finds the tab conversion unhelpful, there's a discussion on meta...

– trichoplax – 2016-10-25T09:28:24.943

0

Python, 68 bytes

n=2
while"".join(str((i+2)**n)[0]for i in range(8))!="23456789":n+=1

Try it online

Tries to answer one of Gelfand's Questions.

  1. Will the row "23456789" ever appear for n>1? None does for n<=10^5. ...

mbomb007

Posted 2016-10-21T23:02:55.273

Reputation: 21 944

0

Clojure, 154 bytes

(loop[x 82001](if(= 0(reduce +(map{true 1 false 0}(for[y(range 3 6)](true?(for[z(str(range 2 y))](.indexOf z(Integer/toString x y))))))))x(recur(inc x))))

Checks if there's a number above 82,000 that only contains 0's and 1's for base 2 all the way to base 5. In other words, it checks if there's another number in this sequence.

In that special group, there are only 3 numbers: 0, 1 and 82,000. There are no more numbers that follow that rule that are less than approximately 3*10^19723.

clismique

Posted 2016-10-21T23:02:55.273

Reputation: 6 600

0

Pyt, 14 bytes

27*²0`ŕĐ₫+Đ₽¬ł

Port of mbomb007's answer.

mudkip201

Posted 2016-10-21T23:02:55.273

Reputation: 833

0

Pushy, 13 bytes

7$h&fh&r2e=?i

Try it online!

This program attempts to find a solution to Brocard's Problem - it will keep running until it finds a \$n \ge 8\$ such that \$ n! +1=m^2, m \in \mathbb{N} \$

FlipTack

Posted 2016-10-21T23:02:55.273

Reputation: 13 242

0

R, 30 bytes, arguable whether it is deterministic

while(any(sample(2,654,T)>1))1

R's default random number generator has equidistribution in 653 consecutive dimensions but it is not known to in 654 dimensions. Thus there may or may not be a sequence of pseudorandom numbers that sample the lowest element from a given vector 654 times in a row (here the vector 1:2).

Since R's RNG is periodic (albeit with very long period), I claim that this is deterministic since it will eventually loop round to the start. Your opinions may differ, of course.

JDL

Posted 2016-10-21T23:02:55.273

Reputation: 1 135

0

Python 3, 101 bytes

I know it's longer than many others, but I spent a lot of time seeing how short I could golf this.

This attempts to disprove Euler's Sum of Powers Conjecture for k=6 (there exists no positive integer solution to the Diophantine equation A^6+B^6+C^6+D^6+E^6==F^6), for which no counterexample has been found.

R=[1]
while 1:R+=[R[-1]+1];eval(("[1/("+"+%s**6"*5+"!=%%s**6)%s]"%("for %s in R "*6))%(*"ABCDEF"*2,))

In Python 2 (104 bytes):

R=[1]
while 1:R+=[R[-1]+1];eval(("[1/("+"+%s**6"*5+"!=%%s**6)%s]"%("for %s in R "*6))%tuple("ABCDEF"*2))

Less golfed:

x=2
while 1:
    R=range(1,x)
    [1/(A**6+B**6+C**6+D**6+E**6!=F**6)for F in R for E in R for D in R for C in R for B in R for A in R]
    x+=1

Mathy version with no eval:

R=range
x=2
while 1:
    for i in R(x**6):1/(sum(map(lambda x:x**6,[1+(i%x**-~j/x**j)for j in R(6)]))-i%x-1)
    x+=1

Alternate reference: Euler's Sum of Powers Conjecture - MathWorld

mbomb007

Posted 2016-10-21T23:02:55.273

Reputation: 21 944