473,386 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Shortest prime number program

I figured someone out there must have written a minimal code size prime
number generator. I did not find one after a bit of searching around.
For primes up to 100 the best I could do was 70 characters (including
spaces):

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]

Feb 11 '06 #1
19 7448
swisscheese wrote:
I figured someone out there must have written a minimal code size prime
number generator. I did not find one after a bit of searching around.
For primes up to 100 the best I could do was 70 characters (including
spaces):

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]


A more straightforward and somewhat shorter solution:

r=range(2,99)
[x for x in r if [x%d for d in r].count(0)<2]

I'm sure it can be made shorter still.
Feb 11 '06 #2
At 58, very nice :-) Building on yours we get 57:
r=range(2,99)
[x for x in r if sum([x%d==0 for d in r])<2]

Feb 11 '06 #3
On Sat, 11 Feb 2006 02:03:46 -0800, swisscheese wrote:
I figured someone out there must have written a minimal code size prime
number generator. I did not find one after a bit of searching around.
For primes up to 100 the best I could do was 70 characters (including
spaces):

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]


I swore I'd never play Python golf.

p,r=[],range(2,99)
while r:p,r=p+r[:1],[x for x in r if x%r[0]]

And the result's in p.

--Ian Bygrave

Feb 11 '06 #4
You can save two bytes with
r=range(2,99)
[x for x in r if sum(x%d==0 for d in r)<2]
Feb 11 '06 #5
>You can save two bytes with

56 - nice catch.
55:
r=range(2,99)
[x for x in r if sum(x%d<1 for d in r)<2]

Feb 11 '06 #6

swisscheese wrote:
I figured someone out there must have written a minimal code size prime
number generator. I did not find one after a bit of searching around.
For primes up to 100 the best I could do was 70 characters (including
spaces):

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]


import gmpy
p=2
while p<99:p=gmpy.next_prime(p)

Feb 11 '06 #7
On Sat, 11 Feb 2006 12:43:23 +0000, Ian Bygrave wrote:
p,r=[],range(2,99)
while r:p,r=p+r[:1],[x for x in r if x%r[0]]

And the result's in p.


Well, given a hypothetical new function 'sieve'

def sieve(f,l):
if not l:
return l
head,tail=l[0],l[1:]
def filter_func(x):
return f(x,head)
tail=filter(filter_func,tail)
return [head]+tail

The prime generation can be reduced to:

from operator import *
sieve(mod,range(2,99))

Is there any precedent for such a function, or any other uses?

--Ian Bygrave

Feb 11 '06 #8
On Sat, 11 Feb 2006 13:33:58 +0000, Ian Bygrave wrote:
Well, given a hypothetical new function 'sieve'
which should have been:

def sieve(f,l):
if not l:
return l
head,tail=l[0],l[1:]
def filter_func(x):
return f(x,head)
tail=filter(filter_func,tail)
return [head]+sieve(f,tail)
The prime generation can be reduced to:

from operator import *
sieve(mod,range(2,99))


--Ian Bygrave

Feb 11 '06 #9
On 2006-02-11, swisscheese <ji******@miclog.com> wrote:
You can save two bytes with


56 - nice catch.
55:
r=range(2,99)
[x for x in r if sum(x%d<1 for d in r)<2]


And if this were FORTRAN:

r=range(2,99)
[xforxinrifsum(x%d<1fordinr)<2]

;)

--
Grant Edwards grante Yow! Hmmm... a CRIPPLED
at ACCOUNTANT with a FALAFEL
visi.com sandwich is HIT by a
TROLLEY-CAR...
Feb 11 '06 #10

swisscheese wrote:

r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]


How about:

[2]+[x for x in range(1,99) if 2**x%x==2]

Mark

Feb 11 '06 #11
di******@gmail.com schrieb:
How about:

[2]+[x for x in range(1,99) if 2**x%x==2]


If the range goes beyond 340, it also gives non-primes...

-- Christoph
Feb 11 '06 #12
di******@gmail.com wrote:
swisscheese wrote:
r=range(2,99)
m=[x*y for x in r for y in r]
[x for x in r if not x in m]

How about:

[2]+[x for x in range(1,99) if 2**x%x==2]


43.

I'll be chewing on this one for a while. Thank you. :)
Feb 11 '06 #13
> [2]+[x for x in range(1,99) if 2**x%x==2]

42 - brilliant!
41:
[2]+[x for x in range(1,99)if 2**x%x==2]
.... although it appears Christoph is right that it's not scalable.

Feb 11 '06 #14
This is a little shorter :-)

[2]+[x for x in range(2,99)if 2**x%x==2]

Bye,
bearophile

Feb 11 '06 #15
> 42
Make that 41 and 40.

Feb 11 '06 #16
Christoph Zwerschke wrote:
di******@gmail.com schrieb:
How about: [2]+[x for x in range(1,99) if 2**x%x==2]
If the range goes beyond 340, it also gives non-primes...


[2,3]+[x for x in range(1,99) if 2**x%x==2 and 3**x%x==3]
[2,3,5]+[x for x in range(1,99) if 2**x%x==2 and 3**x%x==3 and 5**x%x==5]

SCNR, Ralf

PS: They both break at 561, and further strengthening of the
condition will not help. Manual loop unrolling as follows works:

[2,3,... <insert all primes here>]+[x for x in range(1,99) if False]

For sufficiently small values of 99, this will also be a rather
short program.
Feb 11 '06 #17

While not nearly the shortest proposed thus far, I'm fond of:

from itertools import count, ifilter
def sieve(s=count(2)):
while 1:p=s.next();s=ifilter(p.__rmod__,s);yield p

It will generate quite a large number of primes before blowing up (at
least 50,000 primes, p=611,957) and it's much faster than the other
submissions thus far that can generate a more or less arbitrary number
of primes. It's still much slower than Alex Martelli's version in the
cookbook though.

[And yes I know that you can shave off one character by importing
ifilter as i, but that's too much ick for too little gain. There may
well be other, more fruitful ways to compact it though]

-tim

Feb 12 '06 #18
Tim Hochberg wrote:
from itertools import count, ifilter
def sieve(s=count(2)):
while 1:p=s.next();s=ifilter(p.__rmod__,s);yield p


Nice!

-- Christoph
Feb 12 '06 #19

In the spirit of pointless pessimization and obfuscation I have crushed
something very similar to Alex Martelli's eratosthenes function onto a
single line. It's truly monstrous, but somewhat entertaining [Some
preemptive linebreaks added]:

def short():import itertools as it;D={};g=D.get;return (
q for q in it.count(2) if
D.__setitem__(it.dropwhile(D.__contains__,
xrange(g(q,q)+q,2**30,g(q,q))).next(),g(q,q))
or q not in D and D.pop(q,1))
I'm sure there's a lesson to this somewhere. Something like I need to
find something better to do with my spare time.

-tim

Feb 13 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Greg Brunet | last post by:
In doing some testing of different but simple algorithms for getting a list of prime numbers, I ended up getting some results that seem a bit contradictory. Given the following test program...
11
by: lostinpython | last post by:
I'm having trouble writing a program that figures out a prime number. Does anyone have an idea on how to write it? All I know is that n > 2 is prim if no number between 2 and sqrt of n...
0
by: AshifToday | last post by:
this was my and my frineds little project in earlier classes, the program seperates the composite and prime numbers in two sections of the screen ===================== /* This program has...
7
by: brian.digipimp | last post by:
Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. (Note: An even number is prime if it is 2. An odd...
2
by: wudoug119 | last post by:
This is my code and it will take any number that I input and say it is a prime number. Please help me... int Prime(int prime) //declares isPrime as a function using integers { ...
2
by: QHorizon | last post by:
Hello, I'm new to Python (I've learned everything up to iterators so far) and fairly new to Programming. This would be my first real program: #Coordinate Geometry (The whole program is not...
3
by: rcarwise | last post by:
Iam having trouble getting started on this program and wanted to know if I could get help on writing a method and loops to get started. this is the program that I have to do: Write a...
12
by: electric916 | last post by:
I have a homework assignment i Am totally confused on. I started with a basic code to determine if a number is prime or not, but need guidance from here. I will post assignment details then what I...
6
by: sigkill9 | last post by:
I'm doing some reading in a python book and am doing one of the chapter exercises but I cant figure out how to get it to work and was hoping some of you python guru's could help out? Heres...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.