Python - prime numbers - python

I am creating a program in python which adds up the total of all the prime numbrs up to 10. My code so far is:
total = 0
for i in range (10):
for a in range (2,i):
if i % a == 0:
break
else:
total += i
break
print total
My code does not include 2 as a prime number but does include 9. Can anybody spot the error?

Your else: clause needs to be with the for loop not if statement and no break.
As pointed out 2 drops through immediately, which is perfectly okay as it is prime and the else clause is executed:
total = 0
for num in range(2, 10): # Start from 2
for i in range(2, num):
if num%i==0:
break # Not prime, break causes else clause not to be executed
else:
total += num
print total
17
For very low numbers this will be fine, though you really only need to check to the sqrt of num.

Related

Problem with finding 10,001th prime number: 1 off

"""7. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"""
countprime=0
n=2
def prime(number):
for factors in range(2, number):
if number%factors==0:
return False
break
return True
while countprime!=10001:
if prime(n)==True:
countprime+=1
n+=1
print(n)
The answer is supposed to be 104743, but for some reason my brute force program gets 104744, 1 more. Does anyone know why it is one off?
while countprime != 10001:
if prime(n)==True:
countprime+=1
n+=1
When you find a prime number, you always move on to the next number. So, after finding the correct answer, you add up 1 and get 104744.
Try to firstly add 1, and then check if it's prime.
Here is an example:
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1
You need to break your loop immediately when countprime == 10001 to leave your variable n untouched. A possible way:
while True:
countprime += prime(n)
if countprime == 10001:
break
n += 1
After your program finds the 10001th prime, the value of n is increased by 1 therefore your output is 1 more than the expected answer.
If you use print(n-1), your program will behave as expected.
You're increasing n one last time before your loop exits. If you increase n before checking if it's prime then your countPrime counter and the corresponding prime number will stay in sync (but you'll have to start n at 1 instead of 2):
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1

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):

Using Python calculate the 1000 prime number

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)

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