Utopian Tree Solution Using Lisp


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

The following problem comes from HackerRank:

—–
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle of the tree occurs during the monsoon, when it doubles in height. The second growth cycle of the tree occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after N growth cycles?

Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.

Constraints
1 <= T <= 10 0 <= N <= 60 Output Format For each test case, print the height of the Utopian tree after N cycles. ----- My solution using Common Lisp:

(defun even (x) (= (rem x 2) 0))

(defun findheight (height cycle n) (if (> cycle n)
        height
        (if (even cycle)
          (findheight (+ 1 height) (+ cycle 1) n)
          (findheight (* 2 height) (+ cycle 1) n)
        )))
  

(defun main (x) (if (> x 0)
      (progn 
        (setq n (read-line))
        (format t "~D~%" (findheight 1 1 (parse-integer n)))
        (main (- x 1))
      )))

(setq x (read-line))

(main (parse-integer x))

Leave a Reply

Your email address will not be published. Required fields are marked *