GolfScript, 22/20 (20/19) bytes
n(6?,:|2>{(.p|%-.}do:n
At the cost of speed, the code can be made two bytes shorter:
n(6?,:|2>.{|%2>-}/n*
If the output format specified in the edited question is disregarded (which is what many of the existing answers do), two bytes can be saved in the fast version and one can be saved in the slow one:
n(6?,:|2>{(.p|%-.}do
n(6?,:|2>.{|%2>-}/`
This will print an additional LF after the primes for the fast version, and it will print the primes as an array for the slow one.
How it works
Both versions are implementations of the sieve of Eratosthenes.
The fast version does the following:
Set A = [ 2 3 4 … 999,999 ]
and | = [ 0 1 2 … 999,999 ]
.
Set N = A[0]
and print N
.
Collect every N-th element from |
in C
. These are the multiples of N
.
Set A = A - C
.
If A
is non-empty, go back to 2.
n(6? # Push "\n".pop() ** 6 = 1,000,000.
,:| # Push | = [ 0 1 2 … 999,999 ].
,2> # Push A = [ 2 3 4 … 999,999 ].
{ #
( # Unshift the first element (“N”) of “A”.
.p # Print “N”.
|% # Collect every N-th element from “A” into a new array, starting with the first.
- # Take the set difference of “A” and the array from above.
. # Duplicate the set difference.
}do # If the set difference is non-empty, repeat.
:n # Store the empty string in “n”, so no final LF will get printed.
The slow version works in a similar fashion, but instead of successively removing multiples of the minimum of “A” (which is always prime), it removes multiples of all positive integers below 1,000,000.
Competitiveness
In absence of any built-in mathematical functions to factorize or check for primality, all GolfScript solutions will either be very large or very inefficient.
While still far from being efficient, I think I have achieved a decent speed-to-size ratio. At the time of its submission, this approach seems to be the shortest of those that do not use any of the aforementioned built-ins. I say seems because I have no idea how some of the answers work...
I've benchmarked all four submitted GolfScript solutions: w0lf's (trial division), my other answer (Wilson's theorem) and the two of this answer. These were the results:
Bound | Trial division | Sieve (slow) | Wilson's theorem | Sieve (fast)
----------+--------------------+--------------------+------------------+----------------
1,000 | 2.47 s | 0.06 s | 0.03 s | 0.03 s
10,000 | 246.06 s (4.1 m) | 1.49 s | 0.38 s | 0.14 s
20,000 | 1006.83 s (16.8 m) | 5.22 s | 1.41 s | 0.38 s
100,000 | ~ 7 h (estimated) | 104.65 (1.7 m) | 35.20 s | 5.82 s
1,000,000 | ~ 29 d (estimated) | 111136.97s (3.1 h) | 3695.92 s (1 h) | 418.24 s (7 m)
10^6
is even shorter ;) \$\endgroup\$1e6
:-D \$\endgroup\$