Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Racket expt using tail recursion?

If I try this in Racket:

(expt 2 1000)

I get a number many times bigger than all the atoms in the universe:

10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

I can even get crazier with (expt 2 10000) which still only takes a second on my T450 laptop. So as I understand, this is only possible because of tail recursion. Is this correct? If so, is Racket's tail recursion pure functional programming, or are there hidden side-effects going on behind the scenes? Also, when I see Common Lisp's loop, is it based on tail recursion under the hood? In general, I guess I'm wondering how these feats of recursion/looping are possible.

like image 231
147pm Avatar asked Mar 06 '26 07:03

147pm


1 Answers

Racket uses a C library to implement large integers (bignums). The library is called GMP:

https://gmplib.org/manual/Integer-Exponentiation.html

Now the case of 2^n is pretty easy to implement in a binary represetation. You only need a 1 followed by n zeros. That is, GMP can compute the number very fast.

like image 156
soegaard Avatar answered Mar 07 '26 19:03

soegaard