How do you write a program using sieve of Eratosthenes?

2008-01-14 1:47 pm
I want very simple and clear program and pls be quick about that. THX!

Very appreciate =)

回答 (1)

2008-01-14 7:39 pm
✔ 最佳答案
I wrote this program in python. Here is an outline:

1) Check if a number, num, is in our nextFactor table
1a) Yes: add num + our number from the nextFactor table (because it too must be non prime), remove that factor from the table. Skip to the next iteration
1b) No: Check if the number is a new prime that we haven't seen already, if it is, add it to our list of primes, and add its next factor to our nextFactor table.

http://pastebin.com/f781e43a7

You should think about why we would go to all the trouble of doing that rather than this:
1) check if num is prime
1a) Yes: add it to our list of primes
1b) No: do nothing

What is the runtime of the is_prime function? Is it fast or slow?


收錄日期: 2021-04-24 10:04:09
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080114054748AAGePr2

檢視 Wayback Machine 備份