(defun factorial (n)
  (if (<= n 1) 1 (* n (factorial (- n 1)))))

(defun fibonacci (n)
  (if (<= n 1) n (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))

(defun power (x n)
  (if (= n 0) 1 (* x (power x (- n 1)))))

(defun read-int (prompt)
  (loop
     (format t "~a" prompt)
     (finish-output)
     (let ((input (ignore-errors (read))))
       (if (and input (integerp input))
           (return input)
           (format t "Please enter a valid integer.~%")))))

(defun read-number (prompt)
  (loop
     (format t "~a" prompt)
     (finish-output)
     (let ((input (ignore-errors (read))))
       (if (and input (numberp input))
           (return input)
           (format t "Please enter a valid number.~%")))))

(defun math-console ()
  (format t "Welcome to the Lisp Math Console!~%")
  (loop
     (format t "~%Options:~%1) Factorial~%2) Fibonacci~%3) Power~%4) Exit~%")
     (let ((choice (read-int "Enter your choice (1-4): ")))
       (case choice
         (1 (let ((n (read-int "Enter number for factorial: ")))
              (format t "Factorial of ~a = ~a~%" n (factorial n))))
         (2 (let ((n (read-int "Enter number for Fibonacci: ")))
              (format t "Fibonacci of ~a = ~a~%" n (fibonacci n))))
         (3 (let ((x (read-number "Enter the base: "))
                  (n (read-int "Enter the exponent: ")))
              (format t "~a^~a = ~a~%" x n (power x n))))
         (4 (format t "Exiting Math Console. Goodbye!~%") (return))
         (otherwise (format t "Invalid choice. Please enter 1-4.~%"))))))

