iterated square root
If you iteratively apply the square root, you will eventually get a number strictly less than two. Write a function that figures out how many times you have to apply the square root it results in a number less than two.
Examples
(iter-sqrt 1) ;=> 0 (since 1 is already less than 2)
(iter-sqrt 2) ;=> 1 (since the square root of 2 is less than 2)
(iter-sqrt 256) ;=> 4
Bonus: Write it in a way that uses stack frames and in a way that doesn't.
Thanks to this site for the challenge idea where it is considered Medium level in Python.
Email submissions to eric@purelyfunctional.tv before June 28, 2020. You can discuss the submissions in the comments below.
The math underlying my solution (Bernard Fortz.clj): the square root of n is
so taking k times the square root gives
. We want to find k such that
. Taking the log in base n, this leads to
, or
. Taking the log again, we get
. The rest of the code follows easily from appropriate rounding and dealing with the degenerate case n < 2. This leads a constant time solution.