Weird MemoryError issue
John Machin
sjmachin at lexicon.net
Wed Jul 19 16:05:59 EDT 2006
On 20/07/2006 1:58 AM, jedi200581 at yahoo.co.uk wrote:
> Hi,
>
> I'm new at python as I just started to learn it, but I found out
> something weird. I have wrote a little program to compute Mersenne
> number:
>
> # Snipet on
> def is_prime n:
Syntax error. Should be:
def is_prime n:
> for i in range(2, n):
> if (n % i) == 0:
> return 0
> else:
> return 1
>
> for a in range(2, 10000000):
> if (is_prime(a) and is_prime(2**a-1))
Syntax error (missing :)
> print 2**a-1, " is a prime number"
> # Snipet off
>
> This program raise MemoryError. But this one:
>
> # Snipet on
> def is_prime n:
> for i in range(2, n):
> if (n % i) == 0:
> return 0
> return 1 # the change is here
>
> for a in range(2, 10000000):
> if (is_prime(a) and is_prime(2**a-1))
> print 2**a-1, " is a prime number"
> # Snipet off
>
> Does not! Why ??
Neither of the above compiles without error. You may regard this as a
novel suggestion (it's not), but try pasting the actual code that you ran.
When corrected, the versions are functionally equivalent. They give the
same result: on my box, they fell over trying to do
is_prime(536870911), in particular trying to do range(536870911). If
successful, that would produce a list of approx 0.5G elements. On a
32-bit box, that's about 2GB of pointers to objects. Each object has a
reference count, a pointer to its type, and its value -- another 6GB.
Total about 8GB. Use xrange() to avoid the memory grab.
HTH,
John
More information about the Python-list
mailing list