I know there are a number of ways to find the first 100 prime numbers but please help me in my approach. I find the value of count to be increasing but for some reason the while loop condition doesn't apply:
count = 0
while(count <= 20):
for i in range(2, 20):
for j in range(2, i):
if i < j:
print("The number",i,"is prime")
elif i % j == 0:
break
else:
print("The number",i,"is prime")
count = count + 1
print(count)
You could use Sieve of Eratosthenes to find the first n prime numbers:
def primes_upto(limit):
prime = [True] * limit
for n in range(2, limit):
if prime[n]:
yield n # n is a prime
for c in range(n*n, limit, n):
prime[c] = False # mark composites
To get the first 100 primes:
>>> list(primes_upto(542))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, ... ,
499, 503, 509, 521, 523, 541]
To find the first n primes, you could estimate n-th prime (to pass the upper bound as the limit) or use an infinite prime number generator and get as many numbers as you need e.g., using list(itertools.islice(gen, 100)).
This is a more simpler code. We have looped all the numbers from 0 to the number until we have printed 100 prime numbers.
n=0
i=0
while n<100:
i+=1
count=1
for j in range(2,i):
if i%j==0:
count=0
break
if count==1:
print(i,end=' ')
n+=1
If one is looking for a mix of efficiency and simple code, Numpy is worth a try. With some fancy indexing, the following code does the job of implementing the sieve of Eratosthenes.
import numpy as np
ns = np.array(range(2,N))
primes = []
last_prime=2
while last_prime:
primes.append(last_prime)
ns = ns[ns%last_prime != 0]
last_prime = ns[0] if len(ns) > 0 else None
print(primes[:100])
Then just adjust N until you do have 100 primes. A good first guess is something in the order of 100*log(100) ~ 460 (coming from the prime number theorem). This will give 88 primes. Increasing N to the value of 600, you will have enough primes.
prime_count=0
n=1
while(True):
count=0
i=2
n+=1
while(i<=n):
if(n==i):
print(n)
prime_count+=1
elif(n%i==0):
break
i+=1
if(prime_count==100):
break
Related
I'm new to Python. I am trying to count the prime numbers in a given range. Some of the answers that developers have shared are like this:
import math
def count_primes(num):
out = []
for i in range(3,num,2):
if all(i%j!=0 for j in range(3,int(math.sqrt(i))+1,2)):
out.append(i)
print(out)
I wrote a one like this:
import math
def count_primes(num):
out = []
for i in range(3,num,2):
for j in range(3, int(math.sqrt(i))+1,2):
if i%j != 0:
out.append(i)
print(out)
but it doesn't work. Could somebody please help me. Appreciated!
Neither of your example count_primes() functions actually counts primes -- they simply print odd primes. Let's implement a working version of your trial division code, not using confusing booleans and a bad algorithm, but rather taking advantage of Python's else clause on for loops:
def collect_odd_primes(number):
primes = []
for candidate in range(3, number, 2):
for divisor in range(3, int(candidate ** 0.5) + 1, 2):
if candidate % divisor == 0:
break
else: # no break
primes.append(candidate)
return primes
print(collect_odd_primes(40))
OUTPUT
> python3 test.py
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
>
As #MarkRansom comments, the Sieve of Eratosthenes is the better way to go. (+1) Now, let's convert our code to count odd primes instead:
def count_odd_primes(number):
count = 0
for candidate in range(3, number, 2):
for divisor in range(3, int(candidate ** 0.5) + 1, 2):
if candidate % divisor == 0:
break
else: # no break
count += 1
return count
print(count_odd_primes(40))
OUTPUT
> python3 test.py
11
>
Something like this should work. You have to set a variable, because 15%9 != 0, outputs True.
import math
def count_primes(num):
out = []
for i in range(3,num,2):
prime = True
for j in range(3, int(math.sqrt(i))+1,2):
if i%j == 0:
prime = False
if prime:
out.append(i)
print(out)
count_primes(15)
The reason your code and the other is is different is because their use of the all() method. Have a look at how i implemented the method using bools:
import math
def count_primes(num):
out = []
for i in range(3,num,2):
f = True
for j in range(3,int(math.sqrt(i))+1,2):
if i%j==0:
f = False
break
if f:
out.append(i)
print(out)
count_primes(20)
Output:
[3, 5, 7, 11, 13, 17, 19]
You’re appending to the result of the module is unequal to zero. However, it’s only a prime number if all modulo are unequal to zero (there is an all statement missing in your code).
Depending on what program you're running for your code-writing, an alternative method—as opposed to the other answers to this question—would be to write:
n = int(input("Write an integer:"))
m = 2
if n == 1:
print(n, "is a prime number!")
if n == 2:
print(n, "is not a prime number.")
while n > m:
if n % m == 0:
m = m + 1
print(n, "is not a prime number.")
break
if n > n % m > 0:
m = m + 1
print(n, "is a prime number!")
break
It may not be the most efficient, but it gives you a really nice, straight answer to whether or not "x" is a prime number!
I want to iterate through a list in python, detect prime numbers and then add them to another list.
primes = []
nprimes = []
for j in range(0, len(arr)):
num = arr[j] #my list with numbers to check
if num > 1:
for k in range(2, num):
if (num % k) == 0:
nprimes.append(num)
break
else:
primes.append(num)
else:
print(num, " can't be checked, because its smaller than 1")
I have the problem that numbers are always added which are not prime numbers. Also in general the code does not seem to work properly.
If num % k == 0 is false you can't say it's prime directly you have to wait the whole loop, so move the else with the for loop, it'll be executed of no break has been encountered which means it's prime
you may iterate directly on the values for num in arr
you can stop your loop at sqrt(num) you won't find a new divisor after that
for num in arr:
if num > 1:
for k in range(2, int(num ** 0.5) + 1):
if num % k == 0:
nprimes.append(num)
break
else:
primes.append(num)
else:
print(num, " can't be checked, because its smaller than 1")
For learning purposes, let's play with a different approach. First, I recommend you move your trial division code into its own predicate function is_prime(), that returns True or False, so it can be optimized independently of the rest of your code.
Then, I'm going to have itertools.groupby divide the list into prime and non-prime sequences that we splice onto the appropriate lists:
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return number == 2
for divisor in range(3, int(number ** 0.5) + 1, 2):
if number % divisor == 0:
return False
return True
if __name__ == "__main__":
from random import sample
from itertools import groupby
array = sample(range(1, 100), 15)
primes = []
composites = []
for are_prime, numbers in groupby(array, is_prime):
if are_prime:
primes.extend(numbers)
else:
composites.extend(numbers)
print("Numbers:", array)
print("Primes:", primes)
print("Composites:", composites)
OUTPUT
% python3 test.py
Numbers: [91, 87, 10, 2, 11, 24, 21, 12, 46, 61, 15, 32, 57, 22, 5]
Primes: [2, 11, 61, 5]
Composites: [91, 87, 10, 24, 21, 12, 46, 15, 32, 57, 22]
%
There are lots of ways to go about this problem, many of them educational!
I want to find the prime numbers from a list with the following specification:
A) If the numbers are prime, the code should print "[number] is a prime number."
B) If the number is NOT a prime number, it should print "[number] is not a prime number", and a factor of that number, other than 1 and the number itself: "[factor] is a factor of [number]".
check_prime = [26, 39, 51, 53, 57, 79, 85].
for num in check_prime:
for i in range(2, num):
if (num % i) == 0:
print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num))
break
if i == num -1:
print("{} IS a prime number".format(num))
Can someone explain this code? I am unable to understand why there num-1 to find prime number. Why we have not used else statement there?
The answer is that range(2, num) generates numbers starting from 2 up to num-1 because range(0,n) generates numbers in general from 0 to n-1. So your i will run from 2 to num-1. That is why you check if i == num -1: to see if all the values of i have been used to check for the prime number.
Since the inner loop iterates i over range(2, num), i would become num - 1 in the end if the loop does not encounter a break due to finding a divisor, which is how a prime number is determined.
Alternatively, you can use the for-else construct to achieve the goal of determining that the number is a prime only if the loop does not encounter a break in a cleaner way:
for num in check_prime:
for i in range(2, num):
if (num % i) == 0:
print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num))
break
else:
print("{} IS a prime number".format(num))
This is sloppy code.
The logic is that the number is prime if and only if you went through all possible factors less than the number. In this case, i == num-1.
There are better ways to determine whether a number is prime. You can search for "determine prime Python" and get many hits with better code and more straightforward logic.
For instance, this is more clear:
import math
check_prime = [26, 39, 51, 53, 57, 79, 85].
for num in check_prime:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
is_prime = False
break
if is_prime:
print("{} IS a prime number".format(num))
else:
print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num))
Is that easier for you to follow?
I wrote a simple python module that returns the prime numbers up to a given N, using a bool flag is_prime as follows:
def generate_primes_up_to(M):
n = 2
primes = []
while n <= M:
is_prime = True
for p in primes:
if p**2 > n: break
if n % p == 0:
is_prime = False
break
if is_prime: primes.append(n)
n += 1
return primes
if __name__ == '__main__':
generate_primes_up_to(100)
which outputs:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Now, this is actually an ideal case for using the for-else construct, since the number n is prime only if no breaks occurred in the for loop. Thus, I changed the function into:
def generate_primes_up_to(M, flag='nonumpy'):
n = 2
primes = []
while n <= M:
for p in primes:
if p**2 > n: break
if n % p == 0: break
else: primes.append(n)
n += 1
return primes
but now the code outputs:
[2, 5, 27]
I don't understand why the if p**2 > n: break expression is interfering with the flow of the for-else clause. If I remove that line the code yields the right output again.
The condition causing the issue is -
if p**2 > n: break
Lets take an example - 7 , when we are checking if 7 is prime or not , we have already found out that - [2,3,5] are primes, the above condition breaks the for loop, when we check 3 as 3**2 = 9 which is greater than 7 .
Remove that condition and it works fine (Though its very slow).
In the original loop (without the for-else construct) , it worked because in that condition you just broke out of the loop, you did not change the flag is_prime .
With the for..else construct, what happens is that, the else part is only executed when we exit the loop without using break statement.
But in the case of the above condition , we use break statement and hence else part is not executed.
You can also use next:
def generate_primes_up_to(M):
n = 2
primes = []
while n <= M:
if next((False for p in primes if not n % p), True):
primes.append(n)
n += 1
return primes
Problem Statement :
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
My Problem
I have checked through all the code and found that the binary search function is giving a return 1 statement as the output print success. But nothing is added to the final list. Please Help
Program in Python :
from time import time
start = time()
LIMIT = 1000000 # largest limit of the prime numbers
prima = [] # list of primes later to be filled by primes function
# binary search function
def Bsearch(lsta,low,high,search):
if low>high:
return -1
else:
mid = int((low+high)/2)
if search<lsta[mid]:
Bsearch(lsta,low,mid-1,search)
elif search>lsta[mid]:
Bsearch(lsta,mid+1,high,search)
elif search==lsta[mid]:
print("Success!")
return 1
# prime number generating function
# uses sieve of Era** algorithm
# produces correct result tested
def primes(LIMIT):
lsta = {} # temporaty empty dictionary
for i in range(2,LIMIT):
lsta[i] = 1
for i in range(2,LIMIT):
for j in range(i,LIMIT):
if i*j>LIMIT:
break
lsta[i*j] = 0
for i in range(2,LIMIT):
if(lsta[i]==1):
prima.append(i)
primes(LIMIT)
final = []
for item in prima:
x = int(str(item)[::-1])
# real problem here the following statement not inserting any value in final list
if(Bsearch(prima,0,len(prima)-1,x)):
print("Hello!")
print(final)
final.append(item)
print(final)
Quickly generate prime numbers and list out Circular Prime numbers
def primes(max_n):
numbers = range(3, max_n+1, 2)
half = (max_n)//2
initial = 4
for step in xrange(3, max_n+1, 2):
for i in xrange(initial, half, step):
numbers[i-1] = 0
initial += 2*(step+1)
if initial > half:
return [2] + filter(None, numbers)
def rotate(S_list):
S=[]
for i in range(len(S_list)):
S.append(int(S_list[i:]+S_list[:i]))
return set(S)
def circularPrime(limit):
All_primes_in_limit = primes(limit)
circular_prime=[]
reject_list=['0','2','4','5','6','8']
All_primes_in_limit=[i for i in All_primes_in_limit if not any(j in reject_list for j in set(str(i)))]
while All_primes_in_limit:
ShufleSet=rotate(str(All_primes_in_limit[-1]))
PrimesSet=set(All_primes_in_limit)
if not ShufleSet - PrimesSet:
circular_prime+=list(ShufleSet)
All_primes_in_limit=list(PrimesSet-ShufleSet)
circular_prime.sort()
return circular_prime
#for limit value 1000000
print circularPrime(1000000)
This is the fastest possible algorithm for circular prime number listing