TKen
TKen

Reputation: 11

Prime Counting using Scheme

I have created two different methods, using SCHEME, to count how many primes exist between 1 and n. I can't understand why the second method doesn't work.

The one that works -

define (count-primes t)
  (cond((= t 1) 0)
       ((prime? t) (+ 1 (count-primes (- t 1))))
       (else (count-primes(- t 1)))
       )

The one that doesn't work -

(define x 0)
(define (count-primes t)
  (cond((= t 1) x)
       ((prime? t) (+ x 1) (count-primes (- t 1)))
       (else (count-primes(- t 1)))
       )
  )

Upvotes: 1

Views: 184

Answers (1)

rsm
rsm

Reputation: 2560

The problem is with (+ x 1) expression. If you want to increment some variable in Scheme, you have to assign new value to it's name:

(set! x (+ x 1))

It's not enough to simply add some values like you did. It just adds them and then ignores the result because you did not specify what to do with it.

You can also redefine this function to take one more, optional argument and pass x this way, avoiding defining and mutating x separately. Something like:

(define (count-primes t . x)
  (cond ((= t 1) (car x))
        ((prime? t) (+ x 1) (count-primes (- t 1) (+ (car x) 1)))
        (else (count-primes (- t 1) (car x)))))

Note you have to take car of x, because x is actually a list of all optional arguments, but we use only first one, so - car.

Upvotes: 2

Related Questions