+ 1
can you make a prime generator?
Somewhere in a lesson (idk wich one anymore) they had a defined function wich searches for prime numbers. My question is: how do you make that? i came so far: def is_prime(prime) counter = 2 #counts up all the time while True: #calculates if item is divisible if prime % counter != 0: counter += 1 if counter > prime/2: print(prime) counter = 2 prime += 1 # if item us divisible, it goes back to beginning elif Div == integer(): counter = 2 prime += 1 is_prime(5) Pls react if there are mistakes and if you know how to define integer (all whole numbers from 1 to infinity) thank you :D
6 Respostas
+ 2
to check if number a divides number b you can check division remainder ( b % a == 0 means a divides b) so you don't need integer function and then you also don't need Div variable, because you can check directly (prime % counter). as for the function, if i understand correctly, by calling is_prime(5) you want to print prime numbers which are larger than or equal to 5. as for the function, first two checks are ok, but in the third you should have counter > prime/2 instead of Div > prime/2 and that check should be an if inside of the first if because if counter is bigger then the half of the number you are checking, your code will enter your first check and you will be stuck in an infinite loop.
0
I would stop at the square root of 'prime' instead of half way, but the time you save over stopping half way is < 0.001 sec, even when generating a list of large, up to 9 digit primes.
Don't increment prime, increment counter +=2, and start at 1. I believe this is a test function, not a prime generator.
0
thanks :-D. i will try if i van change
0
if you want to see a different approach, i have made an example here:
http://code.sololearn.com/clBAl22f1WC9
but you should definitely do it your way, because it is a good practice.
0
https://code.sololearn.com/cMC3JLRv0T04/?ref=app
in input string type first number and last number of range
0
https://code.sololearn.com/cX3s5Z60JFhS/?ref=app
All prime numbers for 2 to input number.