Python code that creates list of prime numbers - python

Trying to create a list of prime numbers in a fixed range. This is producing non-sensical list but the code makes sense to me.
for number in range(2,100,2):
k = 1
while k*k < number:
k += 2
if number % k == 0:
break
else:
print(number)

there are several bugs in your code.
first, you don't check its divisibility by even numbers, any even number to be exact (including 2)! if it is meant as an optimization approach, make it more generic by not checking the numbers who are known already not to be prime. its called the sieve of eratosthenes
another, is that you don't check the divisibility if n is a square root of a prime number as you pass the k*k = number case.
this is my implementation for a naive n * sqrt(n):
for number in range(2,100):
prime, divisor = True, 2
while prime and divisor ** 2 <= number:
if number % divisor == 0:
prime = False
divisor += 1
if (prime):
print(number)

Change like this:
for number in range(2, 101):
for k in range(2, number):
if (number % k) == 0:
break
else:
print(number)

for number in range(1,100):
counter=0
for test in range(1,number+1):
if number%test==0:
counter=counter+1
if counter<=2:
print(number)

Related

Optimize performance - writing out Prime Numbers

The issue is Prime Numbers -that the solution is not implemented effectively.
I hear about eratosthenes sieve.
What are the other methods of implementing prime numbers - in a more efficient way?
n = int(input())
suma = 0
m = 0
while m < n:
if n > 100000:
break
x = int(input())
if 1 < x < 10000:
for i in range(x):
if x % (i + 1) == 0:
suma += 1
if suma == 2 and x != 2:
m += 1
print('o')
suma = 0
else:
m += 1
print('x')
suma = 0
The one of solution: https://medium.com/#dhruvpatel1057/generate-prime-numbers-in-python-using-segmented-sieve-of-eratosthenes-245b79da6687
You are using a very naive approach for primality checking.
As a general naive but not so much method, I'd recommend using Wilson's theorem as prime checker. Using math.factorial instead of a python loop should provide you with some reasonable speed increase while keeping the code fairly simple.
I hear about eratosthenes sieve - but not idea, how to implement it.
That's not the sieve of eratosthenes proper but what people usually talk about when they mention it is that when you find a prime you go through all your candidates and remove its factors ("sieving" them out hence the name) and the new first candidate is the next prime in the sequence.
There are more efficient primality tests than sieving everything though, check the "primality test" wikipedia page for examples.
This code will generate the amount of prime numbers the user asked for. It is very efficient, and can work out the first thousand prime numbers in milliseconds.
amount = int(input("Enter the amount of prime numbers you would like to see: "))
primes = []
num = 1
while len(primes) < amount:
num += 1
# If num is bigger than 1, and is 2 or is odd, and when divided by all the number from 3 to num's square root plus 1 (excluding even numbers), there is always a remainder.
if num > 1 and (num == 2 or num % 2 != 0) and all(num % divisor != 0 for divisor in range(3, int(num ** 0.5) + 1, 2)):
primes.append(num)
print(f"The first {amount} prime numbers are:\n{primes}")
this is sample code , make a list of prime, and from this list check the number to process is getting divided or not , if it is not getting divided then it is prime else it is not
# your code goes here
x = int(input())
prime =[]
for i in range(2,x):
if i not in prime:
if prime == []:
prime.append(i)
else:
check = 1
for j in prime:
if i%j==0:
check = 0
break
if check:
prime.append(i)
print(prime)

Find prime numbers less than or equal to the number the user has entered with loops. How do I do that?

With this code, I only get to test if the number the user entered is prime or not.
How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered?
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
You can'not print both in one loop, you can do one thing add a loop above your current loop and display each number like this :
num = int(input("Enter a number: "))
if num > 1:
prime = True
for n in range(2, num):
if (num % n) == 0:
print ("Number", num, "is not prime")
break
else:
print("Number", num, "is prime")
#your current code ends here
for j in range(2, num + 1):
# prime numbers are greater than 1
for i in range(2, j):
if (j % i) == 0:
break
else:
print(j)
Your code only check the number entered is prime or not , but you questioned about to get prime numbers from 2 to n (n = number entered by user) for this you run below code with the help of flag bit it will little bit easy for you. i hope it will help you.
Try This i run this code It will Surely help you to find your answer it work in python 3.0 or above
num = int(input("Enter The Number"))
if num > 1:
num = num+1
list = []
for j in range (2,num,1):
flag = 0
for i in range (2,int(j/2)+1,1):
if(j%i)== 0:
flag = 1
break
if flag==0:
list.append(j)
print(list)
else:
print("Enter Number Greater Than 1")
Aside from small things (unused boolean variable) your prime test is also super inefficient.
Let's go through this step by step.
First: To test if a number is prime, you don't need to check all integers up to the number for divisors. Actually, going up to sqrt(num) turns out to be sufficient. We can write a one-liner function to find out if a number is prime like so:
from numpy import sqrt
def is_prime(n):
return n > 1 and all(n%i for i in range(2,int(sqrt(n))+1))
range(2,some_num) gives an iterator through all numbers from 2 up to some_num-1and the all() function checks if the statement n%i is true everywhere in that iterator and returns a boolean. If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality). Even if you don't want to use that function, it's cleaner to separate the functionality into a different function, because in a loop of numbers up to your input you will probably have to check each number for being prime separately anyways.
Second: From here, finding all primes smaller or equal than your input should be pretty easy.
num = int(input("Enter a number:"))
assert num>0, "Please provide a positive integer" # stops with an assertion error if num<=0
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2):
if is_prime(x):
prime_lst.append(x)
The list prime_lst will contain all your sought after prime numbers. I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two. So this way none of the numbers will be divisible by two. Unfortunately this requires me to check if the number itself may be 2, which is a prime. By the twin-prime conjecture we can not simplify this range further without knowing about the input.
Finally: If you really want to find the primes in one loop, change your loop to something along the lines of:
prime_lst = [2] if num > 1 else []
for x in range(3,num+1,2): # outer loop
for i in range(3,int(sqrt(x))+1): # inner loop for check if x is prime
if x%i == 0:
break # breaks the inner loop, number is not prime
else:
prime_lst.append(x)
Edit: Just saw that the second answer here has a good explanation (and an even better way) of writing the one-liner for finding out if a number is prime.

Prime number finder including 2 multiple times

This program makes a list of all prime numbers less than or equal to a given input.
Then it prints the list.
I can't understand why it includes the number 2. When I first designed the program, I initialized the list with primes = [2] because I thought, since 2 % 2 == 0,
if n % x == 0:
is_prime = False
will set is_prime to False. However, that doesn't seem to be the case.
I'm sure there is something going on with the logic of my range() in the for loops that I just don't understand.
I guess my question is: Why is 2 included in the list of primes every time?
import math
limit = int(input("Enter a positive integer greater than 1: "))
while limit < 2:
limit = int(input("Error. Please enter a positive integer greater than 1: "))
primes = []
#Check all numbers n <= limit for primeness
for n in range (2, limit + 1):
square_root = int(math.sqrt(n))
is_prime = True
for x in range(2, (square_root + 1)):
if n % x == 0:
is_prime = False
if is_prime:
primes.append(n)
#print all the primes
print("The primes less than or equal to", limit, "are:")
for num in primes:
print(num)
Because you don't enter the second for-loop when you test for n=2 and therefore you don't set is_prime = False.
# Simplified test case:
x = 2
for idx in range(2, int(math.sqrt(x))+1):
print(idx)
This doesn't print anything because range is in this case: range(2, 2) and therefore has zero-length.
Note that your approach is not really efficient because:
you test each number by all possible divisors even if you already found out it's not a prime.
you don't exclude multiples of primes in your tests: if 2 is a prime, every multiple of 2 can't be prime, etc.
There are really great functions for finding prime numbers mentioned in Fastest way to list all primes below N - so I won't go into that. But if you're interested in improvements you might want to take a look.

List previous prime numbers of n

I am trying to create a program in python that takes a number and determines whether or not that number is prime, and if it is prime I need it to list all of the prime numbers before it. What is wrong with my code?
import math
def factor(n):
num=[]
for x in range(2,(n+1)):
i=2
while i<=n-1:
if n % i == 0:
break
i = i + 1
if i > abs(n-1):
num.append(n)
print(n,"is prime",num)
else:
print(i,"times",n//i,"equals",n)
return
Your method only returns whether the 'n' is prime or not.
For this purpose, you don't need a nested loop. Just like this
def factor(n):
num=[]
for x in range(2,(n+1)):
if n % x == 0:
break
if x > abs(n-1):
num.append(n)
print(n,"is prime",num)
else:
print(x,"times",n//x,"equals",n)
return
And then, if you want all the other primes less than n, you can use prime number sieve algorithm.
--------- Update --------------
A modification of your code which can find the other primes (but prime sieve algorithm still has better performance than this)
def factor(n):
num=[]
for x in range(2,(n+1)):
i=2
while i<=x-1:
if x % i == 0:
break
i = i + 1
if i > abs(x-1):
num.append(x)
if n in num:
print num
else:
print str(n) + ' is not num'
return

Finding a prime number

The problem is that you need to find the prime number after the number input, or if the number input is prime, return that. It works fine. It's just not working when the input is print(brute_prime(1000)). It returns 1001 not 1009. The full code is this:
def brute_prime(n):
for i in range(2, int(n**(0.5))):
if n % i == 0:
n += 1
else:
return n
As Barmar suggests, you need to restart the loop each time you increment n. Your range also ends earlier than it should, as a range stops just before the second argument.
def brute_prime(n):
while True:
for i in range(2, int(n**(0.5)) + 1):
if n % i == 0:
break
else:
return n
n = n+1
remember 2 is a prime number. again you can just check the division by 2 and skip all the even number division
def brute_prime(n):
while True:
if n==2:return n
elif n%2 ==0 or any(n % i==0 for i in range(3, int(n**(0.5)+1),2)):
n += 1
else:
return n
You're not restarting the for i loop when you discover that a number is not prime and go to the next number. This has two problems: you don't check whether the next number is a multiple of any of the factors that you checked earlier, and you also don't increase the end of the range to int(n ** 0.5) with the new value of n.
def brute_prime(n):
while true:
prime = true
for i in range(2, int(n ** 0.5)+1):
if n % i == 0:
prime = false
break
if prime:
return n
n += 1
break will exit the for loop, and while true: will restart it after n has been incremented.
as mention by Chris Martin the wise solution is define a isPrime function separately and use it to get your desire number.
for example like this
def isPrime(n):
#put here your favorite primality test
from itertools import count
def nextPrime(n):
if isPrime(n):
return n
n += 1 if n%2==0 else 2
for x in count(n,2):
if isPrime(x):
return x
if the given number is not prime, with n += 1 if n%2==0 else 2 it move to the next odd number and with count check every odd number from that point forward.
for isPrime trial division is fine for small numbers, but if you want to use it with bigger numbers I recommend the Miller-Rabin test (deterministic version) or the Baille-PSW test. You can find a python implementation of both version of the Miller test here: http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python

Categories