Skip to content

Instantly share code, notes, and snippets.

@triclops200
Last active December 21, 2015 00:58
Show Gist options
  • Save triclops200/6223939 to your computer and use it in GitHub Desktop.
Save triclops200/6223939 to your computer and use it in GitHub Desktop.
Collatz Prime Ratio Visualizer
(defmacro while (test &body body)
`(do ()
((not ,test))
,@body))
(defmacro with-gensyms (syms &body body)
`(let ,(mapcar #'(lambda (x) `(,x (gensym))) syms)
,@body))
(defmacro collect-list (end-condition next-value var)
"Generates a list based on the next-value provided."
(with-gensyms (acc)
`(let ((,acc nil))
(while (not ,end-condition)
(push ,var ,acc)
(setq ,var ,next-value))
(nreverse (cons ,var ,acc)))))
(defun collatz (start)
(collect-list (= start 1)
(if (evenp start)
(/ start 2)
(+ 1 (* 3 start)))
start))
(defun fn-ratio (x fn eqc)
(labels ((rec (y e acc)
(if (> y x)
(reverse acc)
(rec
(+ y 1)
(if (funcall eqc (funcall fn y))
(incf e)
e)
(cons (float (/ e y))
acc)))))
(rec 1 0 nil)))
(defun primep (x &optional (p 2))
(cond ((< x 2) nil)
((= x 2) t)
((= 0 (rem x p)) nil)
((>= p (sqrt x)) t)
(t (primep x (+ p 1)))))
(with-open-file (s "data.txt" :direction :output :if-exists :overwrite)
(dolist (x (fn-ratio 5000000 #'(lambda (x) (length (collatz x))) #'primep))
(format s "~a~%" x))
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.axislines import SubplotZero
file = open("data.txt","rU")
xs = []
for line in file:
xs.append(float(line.strip()))
len(xs)
fig = plt.figure(1)
ax = SubplotZero(fig,111,
xlabel="N",
ylabel="Number of Prime Lengthed Chains Less Than or Equal To N Divided By N")
fig.add_subplot(ax)
x = range(1,len(xs)+1)
ax.plot(x,xs)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment