Monday, August 3, 2009

Discrete Maths, ProblemSet#1

These are my solutions to 1st problem set of discrete mathematics course taught at Arsdigita university by Shai Simonson. Other posts relating to this are here.

Scheme Programs are typed here, others are scanned...
(define (find-goals-misses score)
(define (aux goals near-misses)
(let ((tmp (+ (* 11 goals) (* 7 near-misses))))
((> score tmp)
(aux (+ goals 1) near-misses))
((< score tmp)
(aux goals (- near-misses 1)))
`((goals ,goals) (near-misses ,near-misses))))))
(aux 0 (quotient score 7)))

;following code is copied from sicp
;changed a lit bit to make it run on plt-r5rs
(define-syntax cons-stream
(syntax-rules ()
((cons-stream a b)
(cons a (delay b)))))
(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))
(define stream-null? null?)
(define the-empty-stream '())
(define (stream-filter pred stream)
(cond ((stream-null? stream) the-empty-stream)
((pred (stream-car stream))
(cons-stream (stream-car stream)
(stream-filter pred
(stream-cdr stream))))
(else (stream-filter pred (stream-cdr stream)))))
(define (stream-ref s n)
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(define (integers-starting-from n)
(cons-stream n (integers-starting-from (+ n 1))))
(define primes
(stream-filter prime? (integers-starting-from 3))))
(define (square x) (* x x))
(define (divisible? x y) (= (remainder x y) 0))
(define (prime? n)
(define (iter ps)
(cond ((> (square (stream-car ps)) n) #t)
((divisible? n (stream-car ps)) #f)
(else (iter (stream-cdr ps)))))
(iter primes))

;solution to the problem
(define (multiply-n-primes n)
(define (iter ps n a)
(if (= n 0) a
(iter (stream-cdr ps) (- n 1) (* a (stream-car ps)))))
(iter primes n 1))
(define (find-p8-n)
(define (iter i)
(let ((tmp (+ 1 (multiply-n-primes i))))
(if (prime? tmp)
(iter (+ i 1))
(iter 1))
;Ans: 30031
Here are the other solutions...

No comments:

Post a Comment