Advertisement
Guest User

Untitled

a guest
Apr 19th, 2014
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. (defun longest_collatz(n)
  2. (reverse
  3. (maxlist
  4. (loop for x from 1 to n
  5. collect (list x (length (collatz x)))))))
  6.  
  7. (defun collatz (n)
  8. (if (<= n 1)
  9. '(1)
  10. (if (= (mod n 2) 0)
  11. (cons (/ n 2) (collatz (/ n 2)))
  12. (cons (+ (* n 3) 1) (collatz (+ (* n 3) 1))))))
  13.  
  14. (defun maxlist (z)
  15. (if (> (length z) 1)
  16. (if (< (cadr (elt z 0)) (cadr (elt z 1)))
  17. (maxlist (cdr z))
  18. (maxlist (cons (elt z 0) (cddr z))))
  19. (car z)))
  20.  
  21. (defun collatz (n &optional acc)
  22. (unless (plusp n)
  23. (error "~s(~s): positive argument is required" 'collatz n))
  24. (if (= n 1)
  25. (nreverse (cons 1 acc))
  26. (let ((next (if (evenp n)
  27. (ash n -1) ; same as (mod n 2)
  28. (1+ (* n 3)))))
  29. (collatz next (cons next acc)))))
  30.  
  31. (defun collatz_length2 (n cnt)
  32. (if (<= n 1)
  33. cnt
  34. (if (= (mod n 2) 0)
  35. (collatz_length2 (/ n 2) (1+ cnt))
  36. (collatz_length2 (+ (* n 3) 1) (1+ cnt)))))
  37.  
  38. (defun collatz_length (n) (collatz_length2 n 1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement