Dear all, I recently wanted to count the number of primes in the sequences 2^n+3 and 2^n-3 (and a few more besides) where n is a positive integer.
After a while I realised that I had no real idea how to do this in racket / scheme. I think part of my problem is that I really think of the problem in an imperative way, i.e. "for each n check whether 2^n+3 is prime and if so add one to a count". The program at the bottom of my email is what I came up with. I hope it is clear. I think a more idiomatic racket approach would be to use the for looping construct but I couldn't quite figure out how to make this do what I wanted. I can imagine improving the below by modifying the count-primes-in-seq procedure to take several "formulas" so I can deal with several sequences at once. However, the code below is quite slow even just for one sequence so I imagine that a different approach entirely is what is needed. So, my question is this: how would you more experienced racketeers write code for something like this? I quickly threw together a naive program in Python (a language I'm not too familiar with either) and it was faster to write and runs quicker. However, to be quite honest, I am fonder of racket and would rather just get better at writing racket code for the little things I need to do. Any guidance is appreciated. #lang racket (require math/number-theory) (define (count-primes-in-seq formula bound) (let loop ([n 0] [c 0]) (let ([k (formula n)]) (cond [(> n bound) c] [(and (positive? k) (prime? k)) (loop [+ n 1] [+ c 1])] [else (loop [+ n 1] c)])))) (define bound 1000) ; Primes of the form 2^n-3 (count-primes-in-seq (λ (n) (- (expt 2 n) 3)) bound) ; Primes of the form 2^n+3 (count-primes-in-seq (λ (n) (+ (expt 2 n) 3)) bound) Regards, Bob Heffernan -- You received this message because you are subscribed to the Google Groups "Racket Users" group. To unsubscribe from this group and stop receiving emails from it, send an email to racket-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/20190709120859.7vhyvykfhxtqgk5n%40bob-cit. For more options, visit https://groups.google.com/d/optout.