[Tutor] prime numbers
Gerrit Holl
gerrit@nl.linux.org
Mon Feb 24 18:12:06 2003
ahimsa schreef op maandag 24 februari om 22:14:07 +0000:
> Hello folks
> I am wanting to do an exercise that calls for a function to calculate prime
> numbers. I know that primes can *only* be divided by themself or by 1, and
> nothing else. My difficulty is translating this into parsimonious code
> without labouriously working out all the possible prime numbers as conditions
> for the if control.
> So far I have attempted % and /, and various combinations, but after a while I
> am almost including all the primes anyway. Can someone give me a nudge in the
> right direction please.
>
> Much appreciated
The demo/scripts directory contains exactly this; maybe it can help you.
#! /usr/bin/env python
# Print prime numbers in a given range
def main():
import sys
min, max = 2, 0x7fffffff
if sys.argv[1:]:
min = int(eval(sys.argv[1]))
if sys.argv[2:]:
max = int(eval(sys.argv[2]))
primes(min, max)
def primes(min, max):
if 2 >= min: print 2
primes = [2]
i = 3
while i <= max:
for p in primes:
if i%p == 0 or p*p > i: break
if i%p <> 0:
primes.append(i)
if i >= min: print i
i = i+2
main()
yours,
Gerrit.
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/