Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.forth > #24193

Re: project euler problems in forth

From "WJ" <w_a_x_man@yahoo.com>
Newsgroups comp.lang.forth
Subject Re: project euler problems in forth
Date 2013-07-06 05:47 +0000
Organization A noiseless patient Spider
Message-ID <kr8b1s$ht1$1@dont-email.me> (permalink)
References <2f19628a-24d6-4480-85af-f081e9208643@googlegroups.com> <khlnmd$159$1@dont-email.me>

Show all headers | View raw


WJ wrote:

> > Find the sum of all the primes below two million.
> > 
> > 010.fs
> > 
> > #! /usr/bin/gforth
> > 
> > include isprime.fs
> > 
> > isprime.fs
> > 
> > : isprime ( n -- isprime )
> > dup 2 mod ( check for even)
> > if 
> >   dup 8 < ( check for < 8 - all odd are prime apart from 1)
> >   if 
> >     dup 1 = 1+ ( check for == 1)
> >   else
> >     3 ( start with divisor of 3) 
> >     begin
> >       2dup mod ( check for n mod k)
> >       if
> >         2dup dup * > ( check for k*k > n)
> >         if 
> >           2 + 0  ( bump k and restart loop)
> >         else 
> >           1 1 ( set isprime and terminate loop)
> >         then
> >       else
> >         0 1 ( clear isprime and terminate loop)
> >       then
> >     until
> >     swap drop 
> >   then
> > else 
> >   dup 2 = 0= 1+ ( check for == 2 )
> > then
> > swap drop ( drop all but isprime)
> > ;
> > : pe010
> > 0.
> > 2000000 0 do
> >   i isprime
> >   if
> >     i m+
> >   then
> > loop
> > d. cr
> > ;
> > 
> > pe010
> 
> Factor:
> 
> USING: locals math.primes ;
> 
> :: sum-primes-below ( n -- sum )
>   0 :> sum!
>   2
>   [ dup n < ]
>   [ dup sum + sum!
>     next-prime ]
>   while
>   drop  sum
> ;
> 
> 2,000,000 sum-primes-below .
> 
> 142913828922

Julia:

julia> mapreduce( n -> isprime(n) ? BigInt(n) : 0, +, 1:2_000_000 )
142913828922

Back to comp.lang.forth | Previous | Next | Find similar


Thread

Re: project euler problems in forth "WJ" <w_a_x_man@yahoo.com> - 2013-07-06 05:47 +0000

csiph-web