This commit is contained in:
NaiJi ✨ 2021-05-02 20:55:12 +03:00
parent bc59be89e5
commit 393feda758
1 changed files with 33 additions and 0 deletions

33
sicp-ex-1.33.rkt Normal file
View File

@ -0,0 +1,33 @@
#! /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)