Pavel Krivanek a écrit :
Fun.
Sure it can be improved at cost of more lines of code.
For example, sieve algorithm does not need to start at: i+i, but at i*i.
Time millisecondsToRun: [| n count isPrime |
n := (1 bitShift: 9) * 10000.
count := 0.
isPrime := Array new: n withAll: true.
2 to: n do:
[:i |
(isPrime at: i) ifTrue:
[i + i to: n by: i do:
[:k | isPrime at: k put: false].
count := count + 1]].
count
]
This unfortunately slow things down due to LargeInteger.
So multiples must not be tested above n sqrt,
and n sqrt < (1 bitShift: n hightBit // 2 + 1),
so a faster sieve would be
Time millisecondsToRun: [| n count isPrime nmax |
n := (1 bitShift: 9) * 10000.
count := 0.
isPrime := Array new: n withAll: true.
nmax := (1 bitShift: n highBit // 2 + 1) min: n.
2 to: nmax do:
[:i |
(isPrime at: i) ifTrue:
[i * i to: n by: i do:
[:k | isPrime at: k put: false].
count := count + 1]].
nmax + 1 to: n do:
[:i |
(isPrime at: i) ifTrue:
[count := count + 1]].
count
]
Don't know if it fits the rules of the game however...
Nicolas