In Dr. Racket, how to write a Tetration function

Viewed 184

How would I write a Tetration function in Dr. Racket. This is my code so far:

(define (awesome-tetration k p)
  (cond
    [(= p 1) (expt k p)]
    [else (expt (awesome-tetration k (sub1 p)) (expt k p))]))

If I input

(awesome-tetration 2 3)

My desired output is 2^2^2= 16 However, instead I get:

4294967296

Why is this happening. Can I get some pointers on what's wrong with my code. Thanks.

1 Answers

The recursive step is in correct, you're calling expt more times than needed. The solution is simpler, you just need to to this:

(define (awesome-tetration k p)
  (cond
    [(= p 1) (expt k p)]
    [else (expt k (awesome-tetration k (sub1 p)))]))

Now it works:

(awesome-tetration 2 3)
=> 16
Related