Using Python calculate the 1000 prime number - python

I am attempting to find the 1000 prime number and am trying to do it without cheating memorization or other code. Can you please tell me whether I am on the right track with my code or completely off base?
primes = []
num = 3
while (len(primes)) < 1000:
if num / 2 == 0:
num = num + 1
else:
x = num - 1
for z in range(2,x):
if num % z == 0 :
num = num + 1
else:
primes.append(num)
num = num + 1
print primes[1000]

You've got a few problems (num / 2 == 0 should be num % 2 == 0)1, but really, using continue and break would really help. e.g.
for z in range(2,x): # xrange would be a performance win on python2.x
if num % z == 0 :
num = num + 1
else:
primes.append(num)
num = num + 1
In this loop, you could find yourself incrementing num a whole bunch of times. in reality, you only want to increment it once (to move on to the next number). So here you'd want to break after you increment it. Also, the else statement would need to be on the for loop:
for z in range(2, x):
if num % z == 0:
break # exit the for loop, don't execute `else` clause.
else:
# only executes if `break` was never encountered.
primes.append(num)
# This happens no matter what and should only happen once
# Might as well pull it out of the loop.
num += 1
1the checking for divisibility by 2 is sort of useless here -- It's the first iteration of your loop. If you used xrange (for python2.x) and break as I've described, then this optimization (likely) isn't worth it.
Aside: You don't really need to run the loop from 2 to N - 1, you can actually get away with running the loop from 2 to int(math.sqrt(N)) which makes this lots more efficient :-) although still not the best you can do... The Sieve of Eratosthenes is another algorithm for doing this more efficiently and there's probably even better methods than that (though I'm not an expert in this area)

Related

How to skip a part of the code if a certain condition is met [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached

Prime number calculator produces no output (python)

I am trying to find the 10001st prime using a basic logic:
1) Identify if a number is prime
2) Add it to a list if prime
3) Print the 10001st term in the list
Here is my code:
primelist=[]
import math
i=2
while True:
for x in range(2, int(math.sqrt(i))):
if i % x == 0:
continue
else:
primelist.append(i)
if len(primelist)== 10001:
break
print(primelist[-1])
Is the logic or code fundamentally wrong or inefficient?
What can I do to ameliorate/ make it work?
EDIT
I have incremented i (i+=1) and used all() to check if everything was indivisible, in response to comments
primelist=[2]
import math
i=3
while True:
for x in range(2, int(i**(1/2))):
if all(i%x!=0 for x in range(2, int(math.sqrt(i)))):
primelist.append(i)
i+=1
if len(primelist)== 10001:
break
print(primelist[-1])
Keep the algorithm/code structure the same (no optimization done), so we can easily share several language points, please see inline comments:
primelist=[]
import math
i=2
while True:
#changed to sqrt + 1, the second parameter of range is not inclusive,
#by adding 1, we make sure sqrt itself is included
for x in range(2, int(math.sqrt(i) + 1)):
if i % x == 0:
#you want break not continue, continue will try
#next possible factor, since you already figured out that this
#is not a prime, no need to keep trying
#continue
break
#a for/else block, many python users never encountered this python
#syntax. The else block is only triggered, if the for loop is naturally
#completed without running into the break statement
else:
#a little debugging, to visually confirm we generated all primes
print("adding {}".format(i))
primelist.append(i)
if len(primelist)== 11:
break
#advance to the next number, this is important,
#otherwise i will always be 2
i += 1
print(primelist[-1])
If you would like to optimize the algorithm, search online for "prime sieve".
This one should work if you want to stay with your algorithm:
import math
def is_prime(n):
for x in range(2, int(math.sqrt(n)) + 1):
if n % x == 0:
return False
return True
primelist = []
i = 2
while True:
if is_prime(i) is True:
primelist.append(i)
i += 1
if len(primelist) == 10001:
break
print(primelist[-1])
Here's a version of your code that's a bit faster, and which doesn't use much RAM. We really don't need to build a list of the primes we find. We don't use the numbers in that list to find more primes, and we're really only interested in its length. So instead of building a list we merely keep count of the primes we find.
# Include 2 in the count
count = 1
i = 3
while True:
if all(i % x for x in range(3, int(i ** 0.5) + 1, 2)):
count += 1
if count == 10001:
break
i += 2
print(i)
FWIW, here's a faster solution that uses sieving. We estimate the required size of the sieve using the prime number theorem. Wikipedia gives these bounds for p(n), the n'th prime number, which is valid for n >= 6:
log(n) + log(log(n)) - 1 < p(n) / n < log(n) + log(log(n))
We use the upper bound as the highest number in the sieve. For n < 6 we use a hard-coded list.
To save space, this sieve only holds odd numbers, so we treat the case of p(1) == 2 as a special case.
#!/usr/bin/env python3
''' Use a sieve of Eratosthenes to find nth prime
Written by PM 2Ring 2017.05.01
Sieve code derived from primes1 by Robert William Hanks
See http://stackoverflow.com/a/3035188/4014959
'''
from math import log
from sys import argv
def main():
num = int(argv[1]) if len(argv) > 1 else 10001
if num == 1:
# Handle 2 as a special case
print(1, 2)
return
elif num < 6:
# Use a pre-built table for (3, 5, 7, 11)
primes = [1, 1, 1, 1, 0, 1]
else:
# Compute upper bound from Prime number theorem
x = log(num)
hi = int(num * (x + log(x)))
print('upper bound', hi)
# Create a boolean list of odd primes in range(hi)
primes = [True] * (hi//2)
for i in range(3, 1 + int(hi**0.5), 2):
if primes[i//2]:
primes[i*i//2::i] = [False] * ((hi - i*i - 1) // (2*i) + 1)
# Count the primes until we get the nth one
k = 0
for i, b in enumerate(primes):
if b:
k += 1
if k == num:
break
print(num, 2*i+1)
if __name__ == "__main__":
main()
This code finds p(10001) = 104743 in under 0.15 seconds on my old single core 32 bit 2GHz machine running Python 3.6.0. It finds p(500000) = 7368787 in about 2.2 seconds.

Finding primes in python

I know that python is "slow as dirt", but i would like to make a fast and efficient program that finds primes. This is what i have:
num = 5 #Start at five, 2 and 3 are printed manually and 4 is a multiple of 2
print("2")
print("3")
def isPrime(n):
#It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.
i = 5
w = 2
while (i * i <= n): #You only need to check up too the square root of n
if (n % i == 0): #If n is divisable by i, it is not a prime
return False
i += w
w = 6 - w
return True #If it isnĀ“t ruled out by now, it is a prime
while True:
if ((num % 2 != 0) and (num % 3 != 0)): #save time, only run the function of numbers that are not multiples of 2 or 3
if (isPrime(num) == True):
print(num) #print the now proved prime out to the screen
num += 2 #You only need to check odd numbers
Now comes my questions:
-Does this print out ALL prime numbers?
-Does this print out any numbers that aren't primes?
-Are there more efficient ways(there probably are)?
-How far will this go(limitations of python), and are there any ways to increase upper limit?
Using python 2.7.12
Does this print out ALL prime numbers?
There are infinitely many primes, as demonstrated by Euclid around 300 BC. So the answer to that question is most likely no.
Does this print out any numbers that aren't primes?
By the looks of it, it doesn't. However, to be sure; why not write a unit test?
Are there more efficient ways(there probably are)? -How far will this go(limitations of python), and are there any ways to increase upper limit?
See Fastest way to list all primes below N or Finding the 10001st prime - how to optimize?
Checking for num % 2 != 0 even though you increment by 2 each time seems pointless.
I have found that this algorithm is faster:
primes=[]
n=3
print("2")
while True:
is_prime=True
for prime in primes:
if n % prime ==0:
is_prime=False
break
if prime*prime>n:
break
if is_prime:
primes.append(n)
print (n)
n+=2
This is very simple. The function below returns True if num is a prime, otherwise False. Here, if we find a factor, other than 1 and itself, then we early stop the iterations because the number is not a prime.
def is_this_a_prime(num):
if num < 2 : return False # primes must be greater than 1
for i in range(2,num): # for all integers between 2 and num
if(num % i == 0): # search if num has a factor other than 1 and itself
return False # if it does break, no need to search further, return False
return True # if it doesn't we reached that point, so num is a prime, return True
I tried to optimize the code a bit, and this is what I've done.Instead of running the loop for n or n/2 times, I've done it using a conditional statements.(I think it's a bit faster)
def prime(num1, num2):
import math
def_ = [2,3,5,7,11]
result = []
for i in range(num1, num2):
if i%2!=0 and i%3!=0 and i%5!=0 and i%7!=0 and i%11!=0:
x = str(math.sqrt(i)).split('.')
if int(x[1][0]) > 0:
result.append(i)
else:
continue
return def_+result if num1 < 12 else result

Why won't my code do literally anything?

I'm trying to write some code to compute the thousandth prime number and when I thought I was done I tried to run it but nothing is happening. I don't get errors or anything that should happen according to the code, just literally nothing. I'm running it in windows powershell if that matters. the code is here below. (Python 2.7)
n = 1
all_odd_integers = 2*n+1
prime_number = 2 #cause 3 is the second prime
while prime_number < 1000: #a while loop to get to prime thousand
for i in range (2, (all_odd_integers-1)): #because I want to divide all_odd_integers by all numbers except 1 and itsself and nothing bigger, but bigger than 0
if all_odd_integers % i == 0:
n += 1
print "not a prime" #because, like, if a number can be divided without a reminder it's not a prime
else:
n = n+1
prime_number += 1
print "a prime" #because exactly the opposite of the if-clause, here there is a reminder so prime
if prime_number == 1000:
print "the thousandth prime is %d" (all_odd_integers)
Your code isn't working because you have an infinite while loop, since your for loop isn't even being executed. You almost have the approach right for calculating the primes however.
If you want to print out every prime number as your current code would if it worked, you can much more easily implement something like this :
counter = 1
prime = 3
while counter != 1000:
for x in range(2,prime):
if prime%x == 0:
break
else:
print(prime)
counter += 1
prime += 2
Alternatively, if you only want to print out the thousandth prime I'm sure there are a plethora of more efficient ways, but I would lean towards something like this for simplicity and decent efficiency:
from math import sqrt
counter = 1
prime = 1
while counter < 1000:
prime += 2
for x in range(2,int(sqrt(prime+1)) + 1):
if prime%x == 0:
break
else:
counter += 1
print (prime)
I think you're thinking about this too hard. There are some errors to your code, but really it can all be boiled down to:
counter = 1
n = 2
while True:
n += 1
if all(n % i for i in xrange(2, n)): counter += 1
if counter == 1000: break
print "the thousandth prime is {0}".format(n)
This loops through all numbers between 2 and itself to see if any of them return a 0 remainder when n is divided by them. If none do, it's a prime and counter gets ticked, if not then it goes on to the next number. Once it finds 1000 primes it breaks and prints the thousandth prime is 7919
Some of the things wrong with your code:
all_odd_integers never changes. So when you do for i in range(2, (all_odd_integers-1)) it will never run anything except for i in range(2, 2) which is 0 because range excludes the higher number. all_odd_integers = 2*n+1 is only run once, when all_odd_integers is defined, it doesn't change when n does.
Even if all_odd_integers did update, why would you multiply it by two? Wikipedia has a prime defined as:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
If n was 3 then all_odd_integers would be 7? Why would 3 need to be divided by 4-6?
Just a note: there is no need to check if prime_number is equal to 1000 at the end since that's why the code block broke.
What if you start with n=2 and prime_number = 3? that way you'll reach the for loop.
Like the other anwserers, the condition in the while loop never changes.
Look at your range() call:
range (2, (all_odd_integers-1))
When you call range, there is a start (2) and a stop (all_odd_integers-1).
range(1,5) generates: 1,2,3,4
Look at all_odd_integers:
all_odd_integers = 2*n+1
2*n+1 means 2*1+1 because n = 1 so 2*n+1 = 3 therefore you are calling range(2,2) which gives [] and then the loop is never executed at all.
EDIT: More things
This function gives you your odd integers.
def odd_integers():
odd_integers = []
for i in xrange(1001):
if i/2 != int(i/2);
odd_integers.append(i)
return odd_integers
Here's your new for:
for i in odd_integers():
The condition in your while loop is always true. prime_number doesn't ever change. Look again at your code
for i in range (2, (all_odd_integers-1)):
What is this supposed to do if n=1 and therefore all_odd_integers-1 = 2?
The code under this loop is never executed.
EDIT:
To loop over odd integers just do this:
for i in xrange(1,1000,2):

Python output just shows blinking cursor

I recently started messing around with python and I wrote a program to print out the 1000th prime number but the output only shows a blinking cursor , the code is shown below:
number = 3
count= 1
while count <= 1000:
prime = True
for x in range(2, number):
if number % x == 0:
prime= False
if prime == True:
count = count + 1
if count <= 1000:
number = number + 1
print number
Any help and concise explanation would be appreciated
edit: i just realized the problem. #tichodroma solved the problem but did so by editing the OP post. so when i got to it it was already solved, how ever, he solved it by putting the print into the loop, hence the many numbers waterfall. but it should be outside the loop so as to only show the final result. also - after looking at the OP code before edit, it was written in such a way that it was taking a long time to run, and the "blinking line" was the system working in the background
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
counter = 0
number = 0
while True:
if isprime(number):
counter+=1
if counter == 10000:
break
number+=1
print number

Categories

Resources