[racket] How to verify prime numbers.

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Thu Jul 14 07:02:10 EDT 2011

On Jul 14, 2011, at 1:56 AM, 飞刀 wrote:

> Hello everyone,
> 
> I want a program to verify prime numbers which can be runned in mzscheme.  The following is C source.  I don't konwn how to convert it to lisp.

Well, I wouldn't start from that C code, as the idiomatic way to solve a problem in C is seldom the same as the idiomatic way to solve it in Scheme.  I would start, instead, from the mathematical definition of primeness.

How are the idioms different?  Well, a Scheme programmer probably wouldn't say "I want a fixed-size table of the integers from 1 to 1000000, telling whether each one is or isn't prime;" the Scheme programmer would more likely say "I want a function which, given a positive integer N, gives me a list of all the primes less than N."  And the Scheme programmer would almost certainly do the job with recursion and/or higher order functions rather than loops and assignment statements.

Once you've done this, you should find that your Scheme version is much more mathematically useful than your C version, because the Scheme version will work even if N happens to be larger than 2^31.

Stephen Bloch
sbloch at adelphi.edu




Posted on the users mailing list.