SICP Exercise 1.23 (Skip Even Divisors)

Exercise 1.23.  The smallest-divisor procedure shown at the start of this section does lots of needless testing: After it checks to see if the number is divisible by 2 there is no point in checking to see if it is divisible by any larger even numbers. This suggests that the values used for test-divisor should not be 2, 3, 4, 5, 6, ..., but rather 2, 3, 5, 7, 9, .... To implement this change, define a procedure next that returns 3 if its input is equal to 2 and otherwise returns its input plus 2. Modify the smallest-divisor procedure to use (next test-divisor) instead of (+ test-divisor 1). With timed-prime-test incorporating this modified version of smallest-divisor, run the test for each of the 12 primes found in exercise 1.22. Since this modification halves the number of test steps, you should expect it to run about twice as fast. Is this expectation confirmed? If not, what is the observed ratio of the speeds of the two algorithms, and how do you explain the fact that it is different from 2?

SOLUTION

The code and tests are here.

Observations
============

Generally takes lesser time than when we don't skip even numbers while testing
divisors. But, the number is not near half of the previous number (as we might expect)

Observed Ratios
===============

Observed ratios keep dropping as the numbers get larger and stabilize near
1.5. (For large numbers, the fluctuations caused by other processes in the
computer become less significant.) The reason it is not 2 is that there is an
extra conditional being checked inside the 'next' procedure.



Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions