+ 1
Hi there! How can I numerate strings in result? How to print quantity of prime numbers?
I have a python code: for n in range (2, (int(input("y= ")))): for x in range (2,n): if n%x == 0: break else: c=0 print (n, 'is a prime number')
4 Answers
+ 2
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
primes = [x for x in range(int(input("Number? "))+1) if is_prime(x)]
print(primes)
---------------------
This will create a list containing all prime numbers from 0 to whatever number you input. you can then use any kind of list operation on it, such as:
print(sum(primes))
print(len(primes))
or iterate through it like so:
for prime in primes:
print(prime);
of course you can also use list slicing etc.
if you'd like to do numerical operations on these values, I highly recommend using numpy arrays instead of a list:
import numpy as np
primes = np.asarray(primes)
+ 1
Your code produces a list of all uneven numbers within range, rather than all primes within range. That's because you're merely checking if modulo 2 is 0, a.k.a. the definition of "even number", and return false if that's the case, while returning true if it's not.
Also, note that your code could be refactored to this:
unevens = [x for x in range(int(input ("Number?"))+1) if x%2!=0]
print(unevens)
The for-loop you omitted compared to my example on the other hand checks if modulo equals 0 for any i (where 2 < i < n) and returns true only if that doesn't turn out to be true.
This fits the definition of a prime number: modulo must not equal 0 for any positive integer other than 1 and n. Therefore, we check all integers i where 2 < i < n.
Edits for clarification:
5 divided by 2 equals 2.5:
5 / 2 = 2.5
Now, imagine floats are not allowed, thus:
5 // 2 = 4 with a remainder of 1, thus:
5 % 2 = 1
On the other hand:
4 // 2 = 2 with a remaind of 0, thus:
4 % 2 = 0
By extension, we can use (x % 2 == 0) to evaluate if x is even, and (x % 2 != 0) to evaluate if x is not even, seeing as all even numbers must be dividable by 2 with a remainder of 0.
0
Thanks! It works. But why do we need to use the second string(for i in range(2,n))? we can do like this:
def is_prime(n):
if n%2 == 0:
return False
return True
primes = [x for x in range (int(input ("Number?"))+1) if is_prime(x)]
print(primes)
0
also, I just realized it's much better to use:
for i in range(2, round(n/2)+1): ...
n/2 is just fine as a limit because n % i cannot be 0 for any i > n/2 (except i = n obviously).
the +1 is only needed to make sure 4 isn't added to the list by mistake and doesn't interfere with anything else.
all things considered, this works the same but halves execution time :)