Skip to content

Instantly share code, notes, and snippets.

@kiyoto
Created May 1, 2016 09:10
Show Gist options
  • Save kiyoto/4dbe676711e8e91659b02d72eced5446 to your computer and use it in GitHub Desktop.
Save kiyoto/4dbe676711e8e91659b02d72eced5446 to your computer and use it in GitHub Desktop.
The Collatz Conjecture in PostgreSQL

##QUERY (PostgreSQL 9.4)

WITH RECURSIVE t(n) AS (
  VALUES(1337)
  UNION ALL
  SELECT CASE WHEN n%2=0 THEN n/2 ELSE 3*n+1 END FROM t WHERE n > 1)
SELECT * FROM t

##OUTPUT

  n   
------
 1337
 4012
 2006
 1003
 3010
 1505
 4516
 2258
 1129
 3388
 1694
  847
 2542
 1271
 3814
 1907
 5722
 2861
 8584
 4292
 2146
 1073
 3220
 1610
  805
 2416
 1208
  604
  302
  151
  454
  227
  682
  341
 1024
  512
  256
  128
   64
   32
   16
    8
    4
    2
    1
(45 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment