Monday, August 12, 2013

Problem 7 Redo - Postscript

Problem 7 asks for the 10001st prime - making it one of the many, many Project Euler problems that require having a prime sieve. The first time through, I decided to use Racket to solve this problem because I had written prime sieves in Racket before, and I didn't really feel like writing a sieve in yet another language. However, now that I am continuing beyond problem 20, having Racket/Scheme around for future use will be helpful - so, I decided to redo this problem in a language which I have more experience writing an interpreters for (I have written 3) than I actually have experience writing code in - Postscript. Postscript is a stack based language, just like FALSE, except with more readable code and access to more functions (having access to sqrt, floor, ceiling, etc is nice), so even if postfix is a bit weird, this problem was a breeze compared to FALSE.

/isPrime
{
    
    /x exch def
    /more
    {
        dup 1 add x sqrt floor le
        {
            dup 1 add more
        } if
    } def
    1 more
    /retval true def
    /check
    {
        dup 1 eq not
        {
            x exch mod 0 eq
            {
                /retval false def
                %/poppin { dup 1 eq not { pop poppin } if } def
                %poppin
            }
            if
            check
        }
        { pop }ifelse
    }
    def check retval
} def

/counter 0 def
/current 2 def
/euler7
{
    current isPrime 
    {
        /counter 1 counter add def
    } if
    counter 10001 eq not
    {
        /current 1 current add def
        euler7
    } if
} def
euler7 current pstack

No comments:

Post a Comment