It may be surprisingly difficult to find a prime number and divide it by the prime number ... How do you do it with Python?
When I saw the gif of [Eratosthenes Sieve](https://ja.wikipedia.org/wiki/Eratosthenes Sieve) on Wikipedia, I thought it would be possible to do this, so I tried it. By example? With lambda binding.
do = lambda *x : x
switch = lambda x : x[-1]
primes = (
lambda n : find_primes( range( 2, n + 1 ), ( n + 1 ) ** 0.5, [ ] )
)
find_primes = (
lambda xs, end_point, ys :
switch(
xs[0] <= end_point and do( ys.append( xs[0] )
, find_primes( remove_fst_multiples( xs ) , end_point, ys )
)
or do( ys.extend( xs )
, ys
)
)
)
remove_fst_multiples = (
lambda xs : [ x for x in xs if x % xs[0] ]
)
print primes(100)
Execution result:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
The algorithm is the same as Wikipedia.
primes is a function that just passes values in a nice way. The entity is find_primes.
find_primes is
remove_fst_multiples takes a list and returns a list excluding multiples of the first value of the list.
I received a comment so I tried using it. However, I don't know what it is, so I googled it and replaced the search list with an iterator for the time being. Please see the comments and other announcements on how to use it properly.
from itertools import count, ifilter, takewhile
do = lambda *x : x
switch = lambda x : x[-1]
primes = ( lambda n :
find_primes(
takewhile(lambda x : x < n + 1, count(2))
, ( n + 1 ) ** 0.5
, [ ]
)
)
find_primes = (
lambda xs, end_point, ys :
(lambda a = next( xs ) :
switch(
a <= end_point and do( ys.append( a )
, find_primes( remove_multiples( xs, a ) , end_point, ys )
)
or do( ys.append( a )
, ys.extend(list( xs) )
, ys
)
)
)()
)
remove_multiples = (
lambda xs, a : ifilter(lambda x : x % a , xs )
)
print primes(100)
Recommended Posts