JRS200x
04-13-2005, 05:48 PM
I am trying to make this function (primeList n) where n = some integer.
This function should then return a list of ordered pairs, each pair consisting of an integer and the string "prime" or composite", for example:
(primeList 5) =>
((2 "prime") (3 "prime") (4 "composite") (5 "prime"))
Now I already have code for 3 other functions, 1 called isPrime? which checks if a given value is prime, one called checkDivisors which given an integer and a list of integers, checks to see whether each element in that list is a divisor. Then i also have enumerate, which given n, generates a list from 1 to n.
(define (checkDivisors n ls)
(if (null? ls)
'()
(append (if (zero? (remainder n (car ls) ))
(list (car ls))
(list 0))
(checkDivisors n (cdr ls)))
)
)
(define (isPrime? n)
(if (equal? 0 (sum (checkDivisors n (cdr (enumerate (truncate (sqrt n)))))))
#t
#f
)
)
(define (enumerate n)
(if (= n 1)
(list n)
(append (enumerate (- n 1)) (list n))))
Now, I also have a function called genPrimes, which generate a list of all primes up to n.
(define (genPrimes n)
(if (= n 1)
'()
(if (isPrime? n)
(append (genPrimes (- n 1))(list n))
(genPrimes (- n 1)))))
Now I know that I will have to use cons in order to attach elements of the generated list and the strings "prime" or "composite" but I cannot figure out any way to do this. I think my problem being that I cannot figure out where to recursively call what functions.
Any help would be appreciated.
This function should then return a list of ordered pairs, each pair consisting of an integer and the string "prime" or composite", for example:
(primeList 5) =>
((2 "prime") (3 "prime") (4 "composite") (5 "prime"))
Now I already have code for 3 other functions, 1 called isPrime? which checks if a given value is prime, one called checkDivisors which given an integer and a list of integers, checks to see whether each element in that list is a divisor. Then i also have enumerate, which given n, generates a list from 1 to n.
(define (checkDivisors n ls)
(if (null? ls)
'()
(append (if (zero? (remainder n (car ls) ))
(list (car ls))
(list 0))
(checkDivisors n (cdr ls)))
)
)
(define (isPrime? n)
(if (equal? 0 (sum (checkDivisors n (cdr (enumerate (truncate (sqrt n)))))))
#t
#f
)
)
(define (enumerate n)
(if (= n 1)
(list n)
(append (enumerate (- n 1)) (list n))))
Now, I also have a function called genPrimes, which generate a list of all primes up to n.
(define (genPrimes n)
(if (= n 1)
'()
(if (isPrime? n)
(append (genPrimes (- n 1))(list n))
(genPrimes (- n 1)))))
Now I know that I will have to use cons in order to attach elements of the generated list and the strings "prime" or "composite" but I cannot figure out any way to do this. I think my problem being that I cannot figure out where to recursively call what functions.
Any help would be appreciated.