solutions/Structure and Interpretatio.../sicp-ex-1.33.rkt

33 lines
845 B
Racket
Raw Normal View History

2024-04-16 19:13:00 -04:00
#! /usr/bin/racket
#lang racket/base
(define (square n)
(* n n))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(define (next iterator)
(if (= iterator 2) 3 (+ iterator 2)))
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (next test-divisor)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(define (filtered-accumulate combiner null-value predicate term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (combiner (if (predicate a) (term a) null-value) result))))
(iter a null-value))
(define (range-sum-of-primes a b)
(filtered-accumulate + 0 prime? (lambda (x) x) a (lambda (x) (+ 1 x)) b))
(range-sum-of-primes 2 10)