How to Count Prime Numbers in a Python Script?

  • Context: Python 
  • Thread starter Thread starter mateomy
  • Start date Start date
  • Tags Tags
    Python
Click For Summary

Discussion Overview

The discussion revolves around counting prime numbers in a Python script, focusing on how to enhance an existing script to not only identify primes but also count their occurrences within a user-specified range. Participants explore various programming techniques and share their experiences with Python.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant shares a script that identifies prime numbers but seeks guidance on counting them and improving the script.
  • Another participant suggests using an array to store results for later processing, indicating a lack of familiarity with arrays.
  • A further response elaborates on the nature of arrays, discussing dynamic versus static arrays and the benefits of storing data for later use.
  • One participant proposes a modified version of the original script that includes a counter for primes, explaining the incrementing process of the counter variable.
  • Another participant shares their own experience with a similar Python program, providing a different approach to finding primes using a list and a function to check for primality.
  • Concerns are raised about the efficiency of testing for divisibility only up to a certain index rather than the actual value of primes, with a discussion on the implications of this approach.
  • Clarifications are made regarding the simplicity of the counting mechanism in the script, with participants expressing appreciation for the insights shared.

Areas of Agreement / Disagreement

Participants express various approaches to counting primes and modifying the script, but there is no consensus on the best method or the implications of certain coding practices. The discussion remains open-ended with multiple viewpoints presented.

Contextual Notes

Some participants note limitations in the original script, such as its inability to handle larger prime numbers due to a fixed set of divisors. There are also discussions about the efficiency of the primality test and the handling of array indices versus values.

Who May Find This Useful

Individuals interested in learning Python programming, particularly those focused on algorithms related to prime number identification and counting.

mateomy
Messages
305
Reaction score
0
x=0
y = raw_input("""Up to what number would you like to locate primes?: """)
for i in range(int(y)):
x = x + 1
if x%2 and x%3 and x%5 and x%7:
print x, '--> PRIME'
elif x==2 or x==3 or x==5 or x==7:
print x, '--> PRIME'
elif x==1:
print x
else:
print xI've been on break for the last week and a half and I thought I would spend my time learning Python. I wrote this little script earlier tonight that simply prints out a list of integers within a user specified range and identifies which of them are prime. What I want to do but can't seem to find any documentation on is to have the script count the occurrences of the primes and echo a "There were (blank) number of primes within your specified interval." I have no idea where to look for that sort of thing. I don't want an answer but I would like someone to point me in the direction I need to be going in.

As always,
Thanks.

P.S. This does work, I just want to make it 'better'.
 
Last edited:
Technology news on Phys.org
Hey mateomy.

Have you considered saving results to some array and then processing the array later?
 
chiro said:
Hey mateomy.

Have you considered saving results to some array and then processing the array later?

I've never really done that before. I'm only loosely familiar with arrays in Python as I've only been at this about a week or so. I'm interested in learning though...
 
Well basically an array can be dynamic (i.e. you determine its size from a variable at runtime) or static (you specify a fixed size that the program uses and it is fixed).

Because computers have lots of memory, it's really not a big issue to allocate a huge array because not only do we have lots of memory (RAM), but it's getting faster as well.

Take a look at something like this:

http://pentangle.net/python/handbook/node39.html

Basically the idea is to create an array and then store all your stuff in the array and then you can process it later to get whatever information out that you want after you've done your prime routine above.

So if you want say the first n items in your list, then just access your array and get the first ten items. You can then do whatever you want with those like print them to a file, or the screen (pretty much whatever you want).

If you do more and more programming, what you'll end up doing is you'll create functions that will take some data in and maybe spit some data back out and in this case if you get data out, you call a function which does its thing and then you take that data and do whatever you want with it (maybe give it to another function for instance).
 
Great! I'll take a look at that.

Thank you very much. I'll post back with new questions.
 
I'm confused how I'd get this output piped into an array.
 
mateomy said:
What I want to do but can't seem to find any documentation on is to have the script count the occurrences of the primes and echo a "There were (blank) number of primes within your specified interval." I have no idea where to look for that sort of thing.

Hi mateomy, your program only works up to a maximum count of 120, due to only testing for divisibility with a limited number primes. To make the program more general (able to resolve larger primes) you need to store (and compare against) a "list" of primes currently found, rather than just working with that fixed set of "2,3,5,7".

That being said, with your current program it is an extremely simple matter of just incrementing a counter to achieve what you want. For example,

Code:
x=0
count = 0
y = raw_input('Up to what number would you like to locate primes? : ')
for i in range(int(y)):
  x = x + 1
  if (x%2 and x%3 and x%5 and x%7 and x<>1) or x==2 or x==3 or x==5 or x==7:
    print x, '--> PRIME'
    count += 1
  else:
    print x

print 'There were ',count,' primes in your range.'
I haven't really tried to fix your code (except for not printing "1" as a prime), I've just compacted it a little to make it easier to read.

Note the the line "count += 1" is essentially just shorthand for "count = count + 1". And btw, please use "code" "/code" tags (in square brackets) to preserve your formatting. :smile:
 
Last edited:
Awesome! It's nice to be able to see someone with more experience put out a code that's a little more compact and efficient. I'm trying to get a handle on Python at a rudimentary level so I was pretty excited when it even ran. How does that count function work exactly?
 
Funny, last year I tried to learn something about Python, and program finding n primes was the first thing I did:

Code:
import math

primes = [2]

nth = 30

def prime(n):
   """Checks if number n is prime, using table of primes found earlier."""
   for p in primes[:int(math.sqrt(n))]:
      if n % p == 0:
         return False
   return True

i = 2
while len(primes) < nth:
   i = i+1
   if prime(i):
      print i
      primes.append(i)

n is hard coded, not asked for, but it doesn't change the idea.
 
  • #10
mateomy said:
How does that count function work exactly?
It's so simple I was hoping it would be self explanatory :smile:

The variable "count" is initialized to zero at the start of the program and then incremented by one (in the loop) each time that a prime is found. The line "count += 1" is does the same thing as "count = count + 1", that is, it increments the counter.
 
  • #11
Borek said:
Funny, last year I tried to learn something about Python, and program finding n primes was the first thing I did:

Code:
import math

primes = [2]

nth = 30

def prime(n):
   """Checks if number n is prime, using table of primes found earlier."""
   for p in primes[:int(math.sqrt(n))]:
      if n % p == 0:
         return False
   return True

i = 2
while len(primes) < nth:
   i = i+1
   if prime(i):
      print i
      primes.append(i)

n is hard coded, not asked for, but it doesn't change the idea.

Thanks Borek. Hopefully that will give the OP some ideas on how to extend the program.

There's one little problem you might like to fix though. With the array slice in the line "for p in primes[:int(math.sqrt(n))]", you're effectively testing for divisibility up to the prime whos index in the list is \sqrt{n}, however you should in fact be testing elements whos values are less than \sqrt{n}. You see what I mean, the limit should be on the size of the prime, not on its index.

Actually the code should still work, since the prime counting function \pi(n) is asymptotic to n/\ln(n). And since \sqrt{n}/\ln(\sqrt{n}) \leq \sqrt{n} \leq n/\ln(n) for n>2 then your code should always test enough primes and shouldn't exceed the list bounds. Though in general it will test more primes than needed.
 
Last edited:
  • #12
uart said:
you're effectively testing for divisibility up to the prime whos index in the list is \sqrt{n}

Good point, thanks. It is just a proof I am not thinking in correct categories.
 
  • #13
Oh okay, now I that I see that the 'count' is within the code indent for the 'if' value it IS self explanatory. That's cool. Thanks for the pointers.

Borek, it is weird that you tried the same thing. Your code is much cleaner (not to mention further reaching) than mine, however.
 

Similar threads

  • · Replies 28 ·
Replies
28
Views
5K
  • · Replies 15 ·
Replies
15
Views
2K
  • · Replies 18 ·
Replies
18
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
12
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
Replies
55
Views
7K