James Yeoman
James Yeoman

Reputation: 665

Why does python produce a "memory error" error when calculating x > 1x10^8 primes

I have used vb.net to make the equivalent program to this python one

from colorama import init , Fore


init ( autoreset = True, convert = True)

first = 0
second = 1

print(first)
print(second)

def primes ( temp ) :

    for loopcount in range ( 2 , temp ) :
        if (temp % loopcount) == 0 :
            return False

    return True


while True :
    temp = first + second
    first = second
    second = temp

    if primes ( temp ) == True :
        print(Fore.RED + str(temp))

    else :
       print(temp)

    raw_input("")

and i found that vb.net could do greater than 1x10^300 whereas python can't keep up with anything beyond 1.02x10^8. I don't understand why as I thought that python was great with numbers and number crunching.

FYI: Colorama is the cross platform python library for allowing the colouring of text in the console

Upvotes: 0

Views: 81

Answers (1)

Robᵩ
Robᵩ

Reputation: 168646

Your program crashes because you used range when you wanted xrange.

Quoting the doc:

This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() [occurs when] a very large range is used on a memory-starved machine

Try this instead:

for loopcount in xrange ( 2 , temp ) :

Upvotes: 1

Related Questions