Python print non-prime numbers - python

I have a hackkerank coding challenge to print first n non prime numbers, i have the working code but the problem is that they have a locked code which prints numbers from 1 to n along with the output, in order to pass the test i need to print only the non prime numbers not 1...n numbers along with it. I cant comment the printing part of 1...n as it is blocked. please let me know the idea to print only 1st n non prime numbers:
here is my solution:
def manipulate_generator(generator, n):
if n>1:
ls=[1]
for elm in generator:
if elm>3 and len(ls)<n:
for k in range(2,elm):
if elm%k==0 and elm not in ls:
ls.append(elm)
print(elm)
if len(ls)==n:
return ls
That's the code I added but here is the code that's locked on which I have to write the code above to make it print the number one at a time
def positive_integers_generator():
n = 1
while True:
x = yield n
if x is not None:
n = x
else:
n += 1
k = int(input())
g = positive_integers_generator()
for _ in range(k):
n = next(g)
print(n)
manipulate_generator(g, n)
the point is the for _ in range(k): already prints out number which includes numbers I don't want printed out: This is the desired kind of output I want:for n=10 I want it to print out:
output:
1
4
6
8
9
10
12
14
15
16
I can't change this code but the one above is what I wrote and can be changed... Pleae help me out... Thanks in anticipation

Why not to throw away the numbers which we don't need? Look at this solution which I implemented...
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
def manipulate_generator(generator, n):
if is_prime(n+1):
next(generator)
manipulate_generator(generator, n+1)
Note: I understand that the logic can be improved to make it more efficient. But, its the idea of skipping unnecessary number printing which is important here !

You can print all the numbers from 1 up to the first prime number and then from that first number to the next one until you reach n.

I'm not sure of your hackerrank situation, but printing the first N non-prime numbers efficiently can be done this way.
def non_prime_numbers_till_n(n):
primes = set()
for num in range(2,number + 1):
if num > 1:
for i in range(2, math.sqrt(num)):
if (num % i) == 0:
break
else:
primes.add(num)
result = []
for i in range(1, n):
if i not in primes:
result.append(i)
return result
Depending on what your online editor expects you can either print them, or store them in a list and return the list.
Also bear in mind, you can only check upto the sqrt of the number to determine if its a prime or not.

I eventually came up with this answer which I believe should solve it but id there;s a better way to solve it please add your answers:
def manipulate_generator(generator, n):
for num in range(3,100000):
for q in range(2,num):
if num%q==0 and num>n:
generator.send(num-1)
return
this link python generator helped me to understand python generator

I just solved that right now. Like Swapnil Godse said you need to deal with all special cases to optimize computations. This link might be helpful: click here.
Here is the solution:
from math import sqrt
def is_prime(n):
if (n <= 1):
return False
if (n == 2):
return True
if (n % 2 == 0):
return False
i = 3
while i <= sqrt(n):
if n % i == 0:
return False
i = i + 2
return True
def manipulate_generator(g, n):
if is_prime(n+1):
next(g)
manipulate_generator(g, n+1)

prime = int(input('Please enter the range: '))
prime_number = []
for num in range(prime):
if num > 1:
for i in range(2,num):
if num % i == 0:
break
else:
prime_number.append(num)
print(f'Prime numbers in range {prime} is {prime_number}')
all_number = []
for i in range(2,prime+1):
all_number.append(i)
Non_prime_number = []
for element in all_number:
if element not in prime_number:
Non_prime_number.append(element)
print(f'Non Prime numbers in range {prime} is {Non_prime_number}')

Related

how to make this code on python run faster?

I wrote this snippet on python to resolve project Euler problem #10, but i've been waiting 15 minutes (running this code) and it still doesn't end.
Please help me to improve this code or optimize it.
Here is the snippet:
def prime (n):
f = 1 #flag
for i in range(2,n):
if n % i == 0:
f = 0
return f
s = 0 # Sum
for i in range(2,2000000):
if prime(i) == 1:
s = i + s
print s
import math
def prime (n):
for i in xrange(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
s = 2 # Sum
for i in xrange(3,2000000, 2):
if prime(i):
s += i
print s
It runs in less than 10 seconds for me.
First of all, you want to return from prime once you found out, that a numer is composite.
Second, you do not want to check even numbers. Skip them with xrange(3,2000000, 2)
Third, there is no need to check all numbers from 2 to n in prime, because a*b = b*a
Since you use Python 2 I've replaced range with xrange, it will be a little bit more efficient.
If you want all prime numbers till 2000000, you should consider using Sieve of Eratosthenes.
Code in python : -
def eratosthenes2(n):
multiples = set()
for i in range(2, n+1):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
print(list(eratosthenes2(2000000)))
Source - http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Python
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Beginner looking for advice/help on this code (Python) [duplicate]

I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code.
Here's what I wrote; it prints all the odd numbers instead of primes:
for num in range(1, 101):
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
break
You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n).
If n is divisible by any of the numbers, it is not prime. If a number is prime, print it.
for num in range(2,101):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num)
You can write the same much shorter and more pythonic:
for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
print (num)
As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):
import math
for num in range(2,101):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)
For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.
You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:
import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print (num)
Edited:
As in the first loop odd numbers are selected, in the second loop no
need to check with even numbers, so 'i' value can be start with 3 and
skipped by 2.
import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(3,int(math.sqrt(num))+1, 2)):
print (num)
I'm a proponent of not assuming the best solution and testing it. Below are some modifications I did to create simple classes of examples by both #igor-chubin and #user448810. First off let me say it's all great information, thank you guys. But I have to acknowledge #user448810 for his clever solution, which turns out to be the fastest by far (of those I tested). So kudos to you, sir! In all examples I use a values of 1 million (1,000,000) as n.
Please feel free to try the code out.
Good luck!
Method 1 as described by Igor Chubin:
def primes_method1(n):
out = list()
for num in range(1, n+1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
out.append(num)
return out
Benchmark: Over 272+ seconds
Method 2 as described by Igor Chubin:
def primes_method2(n):
out = list()
for num in range(1, n+1):
if all(num % i != 0 for i in range(2, num)):
out.append(num)
return out
Benchmark: 73.3420000076 seconds
Method 3 as described by Igor Chubin:
def primes_method3(n):
out = list()
for num in range(1, n+1):
if all(num % i != 0 for i in range(2, int(num**.5 ) + 1)):
out.append(num)
return out
Benchmark: 11.3580000401 seconds
Method 4 as described by Igor Chubin:
def primes_method4(n):
out = list()
out.append(2)
for num in range(3, n+1, 2):
if all(num % i != 0 for i in range(2, int(num**.5 ) + 1)):
out.append(num)
return out
Benchmark: 8.7009999752 seconds
Method 5 as described by user448810 (which I thought was quite clever):
def primes_method5(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p]):
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
Benchmark: 1.12000012398 seconds
Notes: Solution 5 listed above (as proposed by user448810) turned out to be the fastest and honestly quiet creative and clever. I love it. Thanks guys!!
EDIT: Oh, and by the way, I didn't feel there was any need to import the math library for the square root of a value as the equivalent is just (n**.5). Otherwise I didn't edit much other then make the values get stored in and output array to be returned by the class. Also, it would probably be a bit more efficient to store the results to a file than verbose and could save a lot on memory if it was just one at a time but would cost a little bit more time due to disk writes. I think there is always room for improvement though. So hopefully the code makes sense guys.
2021 EDIT: I know it's been a really long time but I was going back through my Stackoverflow after linking it to my Codewars account and saw my recently accumulated points, which which was linked to this post. Something I read in the original poster caught my eye for #user448810, so I decided to do a slight modification mentioned in the original post by filtering out odd values before appending the output array. The results was much better performance for both the optimization as well as latest version of Python 3.8 with a result of 0.723 seconds (prior code) vs 0.504 seconds using 1,000,000 for n.
def primes_method5(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p] and sieve[p]%2==1):
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
Nearly five years later, I might know a bit more but I still just love Python, and it's kind of crazy to think it's been that long. The post honestly feels like it was made a short time ago and at the time I had only been using python about a year I think. And it still seems relevant. Crazy. Good times.
Instead of trial division, a better approach, invented by the Greek mathematician Eratosthenes over two thousand years ago, is to sieve by repeatedly casting out multiples of primes.
Begin by making a list of all numbers from 2 to the maximum desired prime n. Then repeatedly take the smallest uncrossed number and cross out all of its multiples; the numbers that remain uncrossed are prime.
For example, consider the numbers less than 30. Initially, 2 is identified as prime, then 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28 and 30 are crossed out. Next 3 is identified as prime, then 6, 9, 12, 15, 18, 21, 24, 27 and 30 are crossed out. The next prime is 5, so 10, 15, 20, 25 and 30 are crossed out. And so on. The numbers that remain are prime: 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.
def primes(n):
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p]):
print p
for i in range(p, n+1, p):
sieve[i] = False
An optimized version of the sieve handles 2 separately and sieves only odd numbers. Also, since all composites less than the square of the current prime are crossed out by smaller primes, the inner loop can start at p^2 instead of p and the outer loop can stop at the square root of n. I'll leave the optimized version for you to work on.
break ends the loop that it is currently in. So, you are only ever checking if it divisible by 2, giving you all odd numbers.
for num in range(2,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
that being said, there are much better ways to find primes in python than this.
for num in range(2,101):
if is_prime(num):
print(num)
def is_prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
The best way to solve the above problem would be to use the "Miller Rabin Primality Test" algorithm. It uses a probabilistic approach to find if a number is prime or not. And it is by-far the most efficient algorithm I've come across for the same.
The python implementation of the same is demonstrated below:
def miller_rabin(n, k):
# Implementation uses the Miller-Rabin Primality Test
# The optimal number of rounds for this test is 40
# See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
# for justification
# If number is even, it's a composite number
if n == 2:
return True
if n % 2 == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in xrange(k):
a = random.randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in xrange(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
Igor Chubin's answer can be improved. When testing if X is prime, the algorithm doesn't have to check every number up to the square root of X, it only has to check the prime numbers up to the sqrt(X). Thus, it can be more efficient if it refers to the list of prime numbers as it is creating it. The function below outputs a list of all primes under b, which is convenient as a list for several reasons (e.g. when you want to know the number of primes < b). By only checking the primes, it saves time at higher numbers (compare at around 10,000; the difference is stark).
from math import sqrt
def lp(b)
primes = [2]
for c in range(3,b):
e = round(sqrt(c)) + 1
for d in primes:
if d <= e and c%d == 0:
break
else:
primes.extend([c])
return primes
My way of listing primes to an entry number without too much hassle is using the property that you can get any number that is not a prime with the summation of primes.
Therefore, if you divide the entry number with all primes below it, and it is not evenly divisible by any of them, you know that you have a prime.
Of course there are still faster ways of getting the primes, but this one already performs quite well, especially because you are not dividing the entry number by any number, but quite only the primes all the way to that number.
With this code I managed on my computer to list all primes up to 100 000 in less than 4 seconds.
import time as t
start = t.clock()
primes = [2,3,5,7]
for num in xrange(3,100000,2):
if all(num%x != 0 for x in primes):
primes.append(num)
print primes
print t.clock() - start
print sum(primes)
A Python Program function module that returns the 1'st N prime numbers:
def get_primes(count):
"""
Return the 1st count prime integers.
"""
result = []
x=2
while len(result) in range(count):
i=2
flag=0
for i in range(2,x):
if x%i == 0:
flag+=1
break
i=i+1
if flag == 0:
result.append(x)
x+=1
pass
return result
A simpler and more efficient way of solving this is storing all prime numbers found previously and checking if the next number is a multiple of any of the smaller primes.
n = 1000
primes = [2]
for i in range(3, n, 2):
if not any(i % prime == 0 for prime in primes):
primes.append(i)
print(primes)
Note that any is a short circuit function, in other words, it will break the loop as soon as a truthy value is found.
we can make a list of prime numbers using sympy library
import sympy
lower=int(input("lower value:")) #let it be 30
upper=int(input("upper value:")) #let it be 60
l=list(sympy.primerange(lower,upper+1)) #[31,37,41,43,47,53,59]
print(l)
Here's a simple and intuitive version of checking whether it's a prime in a RECURSIVE function! :) (I did it as a homework assignment for an MIT class)
In python it runs very fast until 1900. IF you try more than 1900, you'll get an interesting error :) (Would u like to check how many numbers your computer can manage?)
def is_prime(n, div=2):
if div> n/2.0: return True
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
#The program:
until = 1000
for i in range(until):
if is_prime(i):
print i
Of course... if you like recursive functions, this small code can be upgraded with a dictionary to seriously increase its performance, and avoid that funny error.
Here's a simple Level 1 upgrade with a MEMORY integration:
import datetime
def is_prime(n, div=2):
global primelist
if div> n/2.0: return True
if div < primelist[0]:
div = primelist[0]
for x in primelist:
if x ==0 or x==1: continue
if n % x == 0:
return False
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
now = datetime.datetime.now()
print 'time and date:',now
until = 100000
primelist=[]
for i in range(until):
if is_prime(i):
primelist.insert(0,i)
print "There are", len(primelist),"prime numbers, until", until
print primelist[0:100], "..."
finish = datetime.datetime.now()
print "It took your computer", finish - now , " to calculate it"
Here are the resuls, where I printed the last 100 prime numbers found.
time and date: 2013-10-15 13:32:11.674448
There are 9594 prime numbers, until 100000
[99991, 99989, 99971, 99961, 99929, 99923, 99907, 99901, 99881, 99877, 99871, 99859, 99839, 99833, 99829, 99823, 99817, 99809, 99793, 99787, 99767, 99761, 99733, 99721, 99719, 99713, 99709, 99707, 99689, 99679, 99667, 99661, 99643, 99623, 99611, 99607, 99581, 99577, 99571, 99563, 99559, 99551, 99529, 99527, 99523, 99497, 99487, 99469, 99439, 99431, 99409, 99401, 99397, 99391, 99377, 99371, 99367, 99349, 99347, 99317, 99289, 99277, 99259, 99257, 99251, 99241, 99233, 99223, 99191, 99181, 99173, 99149, 99139, 99137, 99133, 99131, 99119, 99109, 99103, 99089, 99083, 99079, 99053, 99041, 99023, 99017, 99013, 98999, 98993, 98981, 98963, 98953, 98947, 98939, 98929, 98927, 98911, 98909, 98899, 98897] ...
It took your computer 0:00:40.871083 to calculate it
So It took 40 seconds for my i7 laptop to calculate it. :)
# computes first n prime numbers
def primes(n=1):
from math import sqrt
count = 1
plist = [2]
c = 3
if n <= 0 :
return "Error : integer n not >= 0"
while (count <= n - 1): # n - 1 since 2 is already in plist
pivot = int(sqrt(c))
for i in plist:
if i > pivot : # check for primae factors 'till sqrt c
count+= 1
plist.append(c)
break
elif c % i == 0 :
break # not prime, no need to iterate anymore
else :
continue
c += 2 # skipping even numbers
return plist
You are terminating the loop too early. After you have tested all possibilities in the body of the for loop, and not breaking, then the number is prime. As one is not prime you have to start at 2:
for num in xrange(2, 101):
for i in range(2,num):
if not num % i:
break
else:
print num
In a faster solution you only try to divide by primes that are smaller or equal to the root of the number you are testing. This can be achieved by remembering all primes you have already found. Additionally, you only have to test odd numbers (except 2). You can put the resulting algorithm into a generator so you can use it for storing primes in a container or simply printing them out:
def primes(limit):
if limit > 1:
primes_found = [(2, 4)]
yield 2
for n in xrange(3, limit + 1, 2):
for p, ps in primes_found:
if ps > n:
primes_found.append((n, n * n))
yield n
break
else:
if not n % p:
break
for i in primes(101):
print i
As you can see there is no need to calculate the square root, it is faster to store the square for each prime number and compare each divisor with this number.
How about this? Reading all the suggestions I used this:
prime=[2]+[num for num in xrange(3,m+1,2) if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1))]
Prime numbers up to 1000000
root#nfs:/pywork# time python prime.py
78498
real 0m6.600s
user 0m6.532s
sys 0m0.036s
Adding to the accepted answer, further optimization can be achieved by using a list to store primes and printing them after generation.
import math
Primes_Upto = 101
Primes = [2]
for num in range(3,Primes_Upto,2):
if all(num%i!=0 for i in Primes):
Primes.append(num)
for i in Primes:
print i
Here is the simplest logic for beginners to get prime numbers:
p=[]
for n in range(2,50):
for k in range(2,50):
if n%k ==0 and n !=k:
break
else:
for t in p:
if n%t ==0:
break
else:
p.append(n)
print p
n = int(input())
is_prime = lambda n: all( n%i != 0 for i in range(2, int(n**.5)+1) )
def Prime_series(n):
for i in range(2,n):
if is_prime(i) == True:
print(i,end = " ")
else:
pass
Prime_series(n)
Here is a simplified answer using lambda function.
def function(number):
for j in range(2, number+1):
if all(j % i != 0 for i in range(2, j)):
print(j)
function(13)
for i in range(1, 100):
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
Print n prime numbers using python:
num = input('get the value:')
for i in range(2,num+1):
count = 0
for j in range(2,i):
if i%j != 0:
count += 1
if count == i-2:
print i,
def prime_number(a):
yes=[]
for i in range (2,100):
if (i==2 or i==3 or i==5 or i==7) or (i%2!=0 and i%3!=0 and i%5!=0 and i%7!=0 and i%(i**(float(0.5)))!=0):
yes=yes+[i]
print (yes)
min=int(input("min:"))
max=int(input("max:"))
for num in range(min,max):
for x in range(2,num):
if(num%x==0 and num!=1):
break
else:
print(num,"is prime")
break
This is a sample program I wrote to check if a number is prime or not.
def is_prime(x):
y=0
if x<=1:
return False
elif x == 2:
return True
elif x%2==0:
return False
else:
root = int(x**.5)+2
for i in xrange (2,root):
if x%i==0:
return False
y=1
if y==0:
return True
n = int(raw_input('Enter the integer range to find prime no :'))
p = 2
while p<n:
i = p
cnt = 0
while i>1:
if p%i == 0:
cnt+=1
i-=1
if cnt == 1:
print "%s is Prime Number"%p
else:
print "%s is Not Prime Number"%p
p+=1
Using filter function.
l=range(1,101)
for i in range(2,10): # for i in range(x,y), here y should be around or <= sqrt(101)
l = filter(lambda x: x==i or x%i, l)
print l
for num in range(1,101):
prime = True
for i in range(2,num/2):
if (num%i==0):
prime = False
if prime:
print num
f=0
sum=0
for i in range(1,101):
for j in range(1,i+1):
if(i%j==0):
f=f+1
if(f==2):
sum=sum+i
print i
f=0
print sum
The fastest & best implementation of omitting primes:
def PrimeRanges2(a, b):
arr = range(a, b+1)
up = int(math.sqrt(b)) + 1
for d in range(2, up):
arr = omit_multi(arr, d)
Here is a different approach that trades space for faster search time. This may be fastest so.
import math
def primes(n):
if n < 2:
return []
numbers = [0]*(n+1)
primes = [2]
# Mark all odd numbers as maybe prime, leave evens marked composite.
for i in xrange(3, n+1, 2):
numbers[i] = 1
sqn = int(math.sqrt(n))
# Starting with 3, look at each odd number.
for i in xrange(3, len(numbers), 2):
# Skip if composite.
if numbers[i] == 0:
continue
# Number is prime. Would have been marked as composite if there were
# any smaller prime factors already examined.
primes.append(i)
if i > sqn:
# All remaining odd numbers not marked composite must be prime.
primes.extend([i for i in xrange(i+2, len(numbers), 2)
if numbers[i]])
break
# Mark all multiples of the prime as composite. Check odd multiples.
for r in xrange(i*i, len(numbers), i*2):
numbers[r] = 0
return primes
n = 1000000
p = primes(n)
print "Found", len(p), "primes <=", n
Adding my own version, just to show some itertools tricks v2.7:
import itertools
def Primes():
primes = []
a = 2
while True:
if all(itertools.imap(lambda p : a % p, primes)):
yield a
primes.append(a)
a += 1
# Print the first 100 primes
for _, p in itertools.izip(xrange(100), Primes()):
print p

Finding the largest prime number "within" a number

For this question, I need to find the largest prime number within a larger number. For the purpose of the example, let's say the larger number is "123456789", then some of the numbers I would have to check are 12, 456, 234567, etc.
I wrote some Python code to figure this out, but it is running very slow for the number I am trying to check. The actual number I am working with is about 10000 digits, so there are a lot of numbers I need to look at. Here is my code:
num = "123456789"
def isPrime(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, long(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def largestPrime():
largest = 2
for i in range(0,len(num)):
for j in range(i+1,len(num)):
if isPrime(long(num[i:j])):
if long(num[i:j]) > largest:
largest =long(num[i:j])
print largest
def main():
largestPrime()
main()
I'm pretty sure this code gives the correct answer, but as I said, it's really slow. Can anyone help me figure out how to speed this up?
Thanks for any help!
I'd probably use the strategy of starting with the total number of digits and seeing if that's prime. Then keep decreasing the digits by one while shifting over to the left to see if that's prime. Let me explain with an example:
123456789
First check the 9-digit number: 123456789
Then check the 8-digit numbers: 23456789, 12345678
Then Check the 7-digit numbers: 3456789, 2345678, 1234567
etc.
One problem I see is that for some large numbers you are going to be testing the same number many times. For example for '123456712345671234567', your code will test '1234567' 3 times. I suggest you make a set that contains no duplicates, then run your prime test on each number. I also think that sorting the numbers is a good idea because we can stop after the first prime is found.
Next if you are dealing with large numbers (e.g. 10000 digits), I suggest using a statistical primality test. Below I made a Miller-Rabin primality test using pseudocode from wikipedia.
I have pretty much rewritten your code :P
import random
num = '3456647867843652345683947582397589235623896514759283590867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876867843652345683947582397589235623896514759283590784235876784235876324650'
def probablyPrime(num, k):
"""Using Miller-Rabin primality test"""
if num == 2 or num == 3:
return True
if num < 2:
return False
if not num & 1:
return False
# find s and d such that n−1 = (2**s)*d with d odd
d = (num-1) >> 1
s = 1
while not (d & 1):
d = d >> 1
s += 1
# run k times
for _ in range(k):
a = random.randint(2, num-2)
x = pow(a, d, num) # more efficient than x = a**d % num
if not (x == 1 or x == num-1):
for _ in range(s-1):
x = (x**2) % num
if x == 1:
return False
if x == num-1:
break
if not x == num-1:
return False
return True
def largestPrime(num):
num_list = set([])
for i in range(0,len(num)+1):
for j in range(i+1,len(num)+1):
inum = int(num[i:j])
# Don't append numbers that have already appeared
if inum not in num_list:
num_list.add(inum)
# Convert to list and sort
num_list = list(num_list)
num_list.sort(reverse=True)
for num in num_list:
print('Checking ' + str(num))
if probablyPrime(num,100):
print('\n' + str(num) + ' is probably the largest prime!')
return
largestPrime(num)
Another way to improve speed might be python's multiprocessing package.
Code:
def isprime(n):
if n == 2:
return str(n)+" is the biggest prime"
if n % 2 == 0:
return isprime(n-1) #not prime, check again for next biggest number
max = n**0.5+1
i = 3
while i <= max:
if n % i == 0:
return isprime(n-1) #not prime, check again for next biggest number
i+=2
return str(n)+" is the biggest prime"
print "Testing 7:",isprime(7)
print "Testing 23:",isprime(23)
print "Testing 2245:",isprime(2245)
print "Testing 222457:",isprime(222457)
print "Testing 727245628:",isprime(727245628)
Output:
>>>
Testing 7: 7 is the biggest prime
Testing 23: 23 is the biggest prime
Testing 2245: 2243 is the biggest prime
Testing 222457: 222437 is the biggest prime
Testing 727245628: 727245613 is the biggest prime

Python Beginner's Loop (Finding Primes)

I'm truly a beginner at python so I apologise for the lack of knowledge, but the reason I'm asking is that reading the Python manual and tutorial (http://docs.python.org/2.7/tutorial) I'm not unable to totally grasp how loops work. I've written some simple programs so I think I get the basics but for whatever reason this program that is meant to list all primes less than or equal to n is not working:
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
print "Done"
The output when I enter 100 for example is:
2 3 5 7 11 13 17 19 23 27 29 31 35 37 41 43 47 53 59 61 67 71 73 79 83 87 89 95 97 101 Done
Which looks almost right but for some reason contains 27, 35, 95, which are composite of course. I've been trying to pick apart the way my loop works but I just don't see where it skips checking for divisibility suddenly. I figured that if someone had a look they could explain to me what about the syntax is causing this. Thanks a bunch!
I would actually restructure the program to look like this:
for p in range(2, n+1):
for i in range(2, p):
if p % i == 0:
break
else:
print p,
print 'Done'
This is perhaps a more idiomatic solution (using a for loop instead of a while loop), and works perfectly.
The outer for loop iterates through all the numbers from 2 to n.
The inner one iterates to all numbers from 2 to p. If it reaches a number that divides evenly into p, then it breaks out of the inner loop.
The else block executes every time the for loop isn't broken out of (printing the prime numbers).
Then the program prints 'Done' after it finishes.
As a side note, you only need to iterate through 2 to the square root of p, since each factor has a pair. If you don't get a match there won't be any other factors after the square root, and the number will be prime.
Your code has two loops, one inside another. It should help you figure out the code if you replace the inner loop with a function. Then make sure the function is correct and can stand on its own (separate from the outer loop).
Here is my rewrite of your original code. This rewrite works perfectly.
def is_prime(n):
i = 2
while i < n:
if n%i == 0:
return False
i += 1
return True
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
if is_prime(p):
print p,
p=p+1
print "Done"
Note that is_prime() doesn't touch the loop index of the outer loop. It is a stand-alone pure function. Incrementing p inside the inner loop was the problem, and this decomposed version doesn't have the problem.
Now we can easily rewrite using for loops and I think the code gets improved:
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
n = int(raw_input("What number should I go up to? "))
for p in range(2, n+1):
if is_prime(p):
print p,
print "Done"
Note that in Python, range() never includes the upper bound that you pass in. So the inner loop, which checks for < n, we can simply call range(2, n) but for the outer loop, where we want <= n, we need to add one to n so that n will be included: range(2, n+1)
Python has some built-in stuff that is fun. You don't need to learn all these tricks right away, but here is another way you can write is_prime():
def is_prime(n):
return not any(n%i == 0 for i in range(2, n))
This works just like the for loop version of is_prime(). It sets i to values from range(2, n) and checks each one, and if a test ever fails it stops checking and returns. If it checks n against every number in the range and not any of them divide n evenly, then the number is prime.
Again, you don't need to learn all these tricks right away, but I think they are kind of fun when you do learn them.
This should work and is bit more optimized
import math
for i in range(2, 99):
is_prime = True
for j in range(2, int(math.sqrt(i)+1)):
if i % j == 0:
is_prime = False
if is_prime:
print(i)
Please compare your snippet with the one pasted below and you will notice where you were wrong.
n = int(raw_input("What number should I go up to? "))
p = 2
while p <= n:
is_prime=True
for i in range(2, p):
if p%i == 0:
is_prime=False
break;
if is_prime==True:
print "%d is a Prime Number\n" % p
p=p+1
you do not re-start the i loop after you find a non-prime
p = i = 2
while p <= n:
i = 2
while i < p:
if p%i == 0:
p += 1
i = 1
i += 1
print p,
p += 1
print "Done"
A while loop executes the body, and then checks if the condition at the top is True, if it is true, it does the body again. A for loop executes the body once for each item in the iterator.
def is_prime(n):
if n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
To find PRIME NUMBER
Let's do a couple more improvements.
You know 2 is the only even prime number, so you add 2 in your list and start from 3 incrementing your number to be checked by 2.
Once you are past the half-way point (see above sqrt and * examples), you don't need to test for a prime number.
If you use a list to keep track of the prime numbers, all you need to do is to divide by those prime numbers.
I wrote my code and each of the above items would improve my code execution time by about 500%.
prime_list=[2]
def is_prime(a_num):
for i in prime_list:
div, rem = divmod(a_num, i)
if rem == 0:
return False
elif div < i:
break;
prime_list.append(a_num)
return True
This in my opinion is a more optimised way. This finds all the prime numbers up to 1,000,000 in less than 8 seconds on my setup.
It is also one of my very first attempts at python, so I stand to be corrected
class prime:
def finder (self):
import math
n = long(raw_input("What number should I go up to? "))
for i in range(2, n):
is_prime = True
if i % 2 == 0:
is_prime = False
for j in range(3, long(math.sqrt(i) + 1), 2):
if i % j == 0:
is_prime = False
break
if is_prime:
print(i)
prime().finder()
print('Enter a Number: ')
number=abs(int(input()))
my_List=[0,1]
def is_prime(n):
if n in my_List:
return True
elif n>=2:
for i in range(2, n):
if n%i == 0:
return False
return True
else:
return False
if is_prime(number):
print("%d is Prime!"%number)
else:
print(number,'is not prime')
for i in range(2, p):
if p%i == 0:
p=p+1
print "%s" % p,
p=p+1
I am going to tell your error only,in line 3 you are incrimenting p but actually what you are missing is your i if your i in previous case is let say 13 then it will check your loop after 13 but it is leaving 2,3,5,7,11 so its an error .that is what happening in case of 27 your i before 27 is 13 and now it will check from 14.and I don't think u need an solution.
def findprime(num):
count = 0
for i in range(1,num+1):
list1 = []
for ch in range(1,i+1):
if i%1==0 and i%ch==0:
list1.append(ch)
if len(list1)==2:
count += 1
print(i,end=", ")
print()
return count
num2 = int(input("enter a number: "))
result=findprime(num2)
print("prime numbers between 1 and",num2,"are",result)
Here's a more extensive example with optimization in mind for Python 3.
import sys
inner_loop_iterations: int = 0
def is_prime(n):
a: int = 2
global inner_loop_iterations
if n == 1:
return("Not prime")
elif n == 2:
return("Prime")
while a * a <= n + 1:
inner_loop_iterations += 1
# This if statement reduces the number of inner loop iterations by roughy 50%
# just weeding out the even numbers.
if a % 2 == 0:
a += 1
else:
a += 2
if n % 2 == 0 or n % a == 0:
return ("Not prime")
else:
return ("Prime")
while True:
sys.stdout.write("Enter number to see if it's prime ('q' to quit): ")
n = input()
if not n:
continue
if n == 'q':
break
try:
n = int(n)
except ValueError:
print("Please enter a valid number")
if n < 1:
print("Please enter a valid number")
continue
sys.stdout.write("{}\n".format(is_prime(n)))
sys.stderr.write("Inner loops: {}\n\n".format(inner_loop_iterations))
inner_loop_iterations=0
This program has two main optimizations, first it only iterates from 2 to the square root of n and it only iterates through odd numbers. Using these optimizations I was able to find out that the number 1000000007 is prime in only 15811 loop iterations.
My fast implementation returning the first 25 primes:
#!/usr/bin/env python3
from math import sqrt
def _is_prime(_num: int = None):
if _num < 2:
return False
if _num > 3 and not (_num % 2 and _num % 3):
return False
return not any(_num % _ == 0 for _ in range(3, int(sqrt(_num) + 1), 2))
_cnt = 0
for _ in range(1, 1000):
if _is_prime(_):
_cnt += 1
print(f"Prime N°: {_:,} | Count: {_cnt:,}")
Better use
for i in range(2, p//2 + 1):

How can I get this Python code to run more quickly? [Project Euler Problem #7]

I'm trying to complete this Project Euler challenge:
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?
My code seem to be right because it works with small numbers, e.g 6th prime is 13.
How can i improve it so that the code will run much more quickly for larger numbers such as 10 001.
Code is below:
#Checks if a number is a prime
def is_prime(n):
count = 0
for i in range(2, n):
if n%i == 0:
return False
break
else:
count += 1
if count == n-2:
return True
#Finds the value for the given nth term
def term(n):
x = 0
count = 0
while count != n:
x += 1
if is_prime(x) == True:
count += 1
print x
term(10001)
UPDATE:
Thanks for your responses. I should have been more clear, I am not looking to speed up the interpreter or finding a faster interpreter, because i know my code isn't great, so i was looking for ways of make my code more efficient.
A few questions to ponder:
Do you really need to check the division until n-1? How earlier can you stop?
Apart from 2, do you really need to check the division by all the multiples of two ?
What about the multiples of 3? 5? Is there a way to extend this idea to all the multiples of previously tested primes?
The purpose of Project Euler is not really to think learn programming, but to think about algorithms. On problem #10, your algorithm will need to be even faster than on #7, etc. etc. So you need to come up with a better way to find prime numbers, not a faster way to run Python code. People solve these problems under the time limit with far slower computers that you're using now by thinking about the math.
On that note, maybe ask about your prime number algorithm on https://math.stackexchange.com/ if you really need help thinking about the problem.
A faster interpreter won't cut it. Even an implementation written in C or assembly language won't be fast enough (to be in the "about one second" timeframe of project Euler). To put it bluntly, your algorithm is pathetic. Some research and thinking will help you write an algorithm that runs faster in a dog-slow interpreter than your current algorithm implemented in native code (I won't name any specifics, partly because that's your job and partly because I can't tell offhand how much optimization will be needed).
Many of the Euler problems (including this one) are designed to have a solution that computes in acceptable time on pretty much any given hardware and compiler (well, not INTERCAL on a PDP-11 maybe).
You algorithm works, but it has quadratic complexity. Using a faster interpreter will give you a linear performance boost, but the quadratic complexity will dwarf it long before you calculate 10,000 primes. There are algorithms with much lower complexity; find them (or google them, no shame in that and you'll still learn a lot) and implement them.
Without discussing your algorithm, the PyPy interpreter can be ridiculously faster than the normal CPython one for tight numerical computation like this. You might want to try it out.
to check the prime number you dont have to run till n-1 or n/2....
To run it more faster,you can check only until square root of n
And this is the fastest algorithm I know
def isprime(number):
if number<=1:
return False
if number==2:
return True
if number%2==0:
return False
for i in range(3,int(sqrt(number))+1):
if number%i==0:
return False
return True
As most people have said, it's all about coming up with the correct algorithm. Have you considered looking at a
Sieve of Eratosthenes
import time
t=time.time()
def n_th_prime(n):
b=[]
b.append(2)
while len(b)<n :
for num in range(3,n*11,2):
if all(num%i!=0 for i in range(2,int((num)**0.5)+1)):
b.append(num)
print list(sorted(b))[n-1]
n_th_prime(10001)
print time.time()-t
prints
104743
0.569000005722 second
A pythonic Answer
import time
t=time.time()
def prime_bellow(n):
b=[]
num=2
j=0
b.append(2)
while len(b)-1<n:
if all(num%i!=0 for i in range(2,int((num)**0.5)+1)):
b.append(num)
num += 1
print b[n]
prime_bellow(10001)
print time.time()-t
Prints
104743
0.702000141144 second
import math
count = 0 <br/> def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
for i in range(2,2000000):
if is_prime(i):
count += 1
if count == 10001:
print i
break
I approached it a different way. We know that all multiples of 2 are not going to be prime (except 2) we also know that all non-prime numbers can be broken down to prime constituents.
i.e.
12 = 3 x 4 = 3 x 2 x 2
30 = 5 x 6 = 5 x 3 x 2
Therefore I iterated through a list of odd numbers, accumulating a list of primes, and only attempting to find the modulus of the odd numbers with primes in this list.
#First I create a helper method to determine if it's a prime that
#iterates through the list of primes I already have
def is_prime(number, list):
for prime in list:
if number % prime == 0:
return False
return True
EDIT: Originally I wrote this recursively, but I think the iterative case is much simpler
def find_10001st_iteratively():
number_of_primes = 0
current_number = 3
list_of_primes = [2]
while number_of_primes <= 10001:
if is_prime(current_number, list_of_primes):
list_of_primes.append(current_number)
number_of_primes += 1
current_number += 2
return current_number
A different quick Python solution:
import math
prime_number = 4 # Because 2 and 3 are already prime numbers
k = 3 # It is the 3rd try after 2 and 3 prime numbers
milestone = 10001
while k <= milestone:
divisible = 0
for i in range(2, int(math.sqrt(prime_number)) + 1):
remainder = prime_number % i
if remainder == 0: #Check if the number is evenly divisible (not prime) by i
divisible += 1
if divisible == 0:
k += 1
prime_number += 1
print(prime_number-1)
import time
t = time.time()
def is_prime(n): #check primes
prime = True
for i in range(2, int(n**0.5)+1):
if n % i == 0:
prime = False
break
return prime
def number_of_primes(n):
prime_list = []
counter = 0
num = 2
prime_list.append(2)
while counter != n:
if is_prime(num):
prime_list.append(num)
counter += 1
num += 1
return prime_list[n]
print(number_of_primes(10001))
print(time.time()-t)
104743
0.6159017086029053
based on the haskell code in the paper: The Genuine Sieve of Eratosthenes by Melissa E. O'Neill
from itertools import cycle, chain, tee, islice
wheel2357 = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
def spin(wheel, n):
for x in wheel:
yield n
n = n + x
import heapq
def insertprime(p,xs,t):
heapq.heappush(t,(p*p,(p*v for v in xs)))
def adjust(t,x):
while True:
n, ns = t[0]
if n <= x:
n, ns = heapq.heappop(t)
heapq.heappush(t, (ns.next(), ns))
else:
break
def sieve(it):
t = []
x = it.next()
yield x
xs0, xs1 = tee(it)
insertprime(x,xs1,t)
it = xs0
while True:
x = it.next()
if t[0][0] <= x:
adjust(t,x)
continue
yield x
xs0, xs1 = tee(it)
insertprime(x,xs1,t)
it = xs0
primes = chain([2,3,5,7], sieve(spin(cycle(wheel2357), 11)))
from time import time
s = time()
print list(islice(primes, 10000, 10001))
e = time()
print "%.8f seconds" % (e-s)
prints:
[104743]
0.18839407 seconds
from itertools import islice
from heapq import heappush, heappop
wheel2357 = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,
4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
class spin(object):
__slots__ = ('wheel','o','n','m')
def __init__(self, wheel, n, o=0, m=1):
self.wheel = wheel
self.o = o
self.n = n
self.m = m
def __iter__(self):
return self
def next(self):
v = self.m*self.n
self.n += self.wheel[self.o]
self.o = (self.o + 1) % len(self.wheel)
return v
def copy(self):
return spin(self.wheel, self.n, self.o, self.m)
def times(self, x):
return spin(self.wheel, self.n, self.o, self.m*x)
def adjust(t,x):
while t[0][0] <= x:
n, ns = heappop(t)
heappush(t, (ns.next(), ns))
def sieve_primes():
for p in [2,3,5,7]:
yield p
it = spin(wheel2357, 11)
t = []
p = it.next()
yield p
heappush(t, (p*p, it.times(p)))
while True:
p = it.next()
if t[0][0] <= p:
adjust(t,p)
continue
yield p
heappush(t, (p*p, it.times(p)))
from time import time
s = time()
print list(islice(sieve_primes(), 10000, 10001))[-1]
e = time()
print "%.8f seconds" % (e-s)
prints:
104743
0.22022200 seconds
import time
from math import sqrt
wheel2357 = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
list_prime = [2,3,5,7]
def isprime(num):
limit = sqrt(num)
for prime in list_prime:
if num % prime == 0: return 0
if prime > limit: break
return 1
def generate_primes(no_of_primes):
o = 0
n = 11
w = wheel2357
l = len(w)
while len(list_prime) < no_of_primes:
i = n
n = n + w[o]
o = (o + 1) % l
if isprime(i):
list_prime.append(i)
t0 = time.time()
generate_primes(10001)
print list_prime[-1] # 104743
t1 = time.time()
print t1-t0 # 0.18 seconds
prints:
104743
0.307313919067

Categories

Resources