Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (defun longest_collatz(n)
- (reverse
- (maxlist
- (loop for x from 1 to n
- collect (list x (length (collatz x)))))))
- (defun collatz (n)
- (if (<= n 1)
- '(1)
- (if (= (mod n 2) 0)
- (cons (/ n 2) (collatz (/ n 2)))
- (cons (+ (* n 3) 1) (collatz (+ (* n 3) 1))))))
- (defun maxlist (z)
- (if (> (length z) 1)
- (if (< (cadr (elt z 0)) (cadr (elt z 1)))
- (maxlist (cdr z))
- (maxlist (cons (elt z 0) (cddr z))))
- (car z)))
- (defun collatz (n &optional acc)
- (unless (plusp n)
- (error "~s(~s): positive argument is required" 'collatz n))
- (if (= n 1)
- (nreverse (cons 1 acc))
- (let ((next (if (evenp n)
- (ash n -1) ; same as (mod n 2)
- (1+ (* n 3)))))
- (collatz next (cons next acc)))))
- (defun collatz_length2 (n cnt)
- (if (<= n 1)
- cnt
- (if (= (mod n 2) 0)
- (collatz_length2 (/ n 2) (1+ cnt))
- (collatz_length2 (+ (* n 3) 1) (1+ cnt)))))
- (defun collatz_length (n) (collatz_length2 n 1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement