Find the prime and non prime numbers: Python - python

I am trying to modify my program to create two empty lists: prime and non_prime.
and test if the random number in the list is a prime number or not a prime number. If the number is prime, I want to append it to prime number list. If not, I want to be able to add it to non_prime list.
I tried to find the prime and non prime number from the random number list but I get the same output for prime and non prime number. Can anyone help me?
import random
def main():
num = [random.randint(1,100) for _ in range (20)]
print(num)
lowest = min(num)
print("The lowest number is: ", lowest)
highest = max(num)
print("The highest number is: ", highest)
total = 0.0
for value in num:
total += value
average = total / len(num)
print("The average is: " , average)
prime = [num]
for a in range (1, 101):
for b in range(2, a):
if a % b == 0:
break
else:
prime.append(a)
print("The prime numbers are: " , prime)
nonprime = [num]
for x in range (1, 101):
for y in range(2, x):
if x % y == 0:
break
else:
nonprime.append(x)
print("The non prime numbers are: " , nonprime)

You could use my handy-dandy one-liner prime-checker!
def is_prime (x): return True if x in [2,3] else not any (x % n == 0 for n in range (2, int (x ** 0.5) + 1))
Now, you use this function in your for loop:
for num in range (1, 101):
if is_prime (num): prime.append (x)
else: nonprime.append (x)
BTW, if anyone wants to help me improve that function (or just wants to understand it), just comment below! It pretty much makes a list of all the factors then returns true or false based on the length of that list (or True if the num is 2 or 3)

Just an optimization tip. In the first loop you could calculate non prime and prime both.
def isPrime(x):
for i in range (sqrt (x)): # from i=2 till sqrt(x)
if x % i == 0: return False
return True
if isPrime (x): prime.append (x)
else: non_prime.append (x)
The above is sieve algorithm

Related

Python code that creates list of prime numbers

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)

Python to list all primes 50 - 1000 , then squaring and checking if prime

I would like to write a program to list all prime numbers 50 - 1000 and then square each of the identified primes and perform a check if any of the numbers are prime or composite.
I have the below code working to list all primes, I am not entirely sure where to start to perform the second check to square the prime numbers and check if prime or composite. Any pointers in the right direction would be much appreciated.
lower = 50
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
By definition, a square can not be prime. However, if you want to test it by your own, I have rewritten your by creating a function called check_prime() which checks whether the number is prime.
def check_prime(number):
temp = []
for i in range(1, number):
if len(temp) > 1:
return False
if number % i == 0:
temp.append(i)
return True
prime = []
for i in range(50, 101):
if check_prime(i):
prime.append(i)
prime_2 = []
for i in prime:
if check_prime(i ** 2):
prime_2.append(i ** 2)
print(prime_2)

Python 3. How do you assign a variable in a function to use in the outer scope of the function?

I am extremely new to programming. I have been working on a project where the user is asked to import a number, which goes through a mathematical series. The output is then put into a function to find the factors of the number. From there I am trying to find the factors that are prime numbers?
This is what i have so far.
enter code here####################################
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)
#####################################
# Factors
#function name nfactors
def nfactors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
fact = nfactors(num)
print(fact)
#####################################
print('The prime numbers are:')
if fact > 1:
# check for factors
for i in range(2,fact):
if (fact % i) == 0:
break
else:
print(fact)
I know this is bad programming but I am trying to learn through doing this project. How can I then take the factors I received as the output of the function and find which factors are prime numbers. I cannot figure out how to name a variable inside the function and use that outside the function, I don't know if this is even possible. If you need any clarifications please let me know. Thanks for any help.
def nfactors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
return i
fact = nfactors(num)
Use the return keyword to return the value of i or whatever it is you would like to use outside of the function!
I seriously hope that you are trying to find the factors of n instead of num as finding the factors of num for a mere number n=12 is a great deal and it'll take several minutes or even hours even with my optimized code.
Anyway assuming you want to find it for n and not num the below code should do your job.
In case you really want to find factors for num, this code will work fine for that too but it'll take too much time. Just change factors = factors(n) to factors = factors(num).
from math import sqrt
#Block 1 (Correct)
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)
#---------------------------------------------------
def factors_(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
list_of_factors = []
for i in range(1, x + 1):
if x % i == 0:
list_of_factors.append(i)
return(list_of_factors) #This returns a list of factors of a given number x
factors = factors_(n) #I am assuming you want to find the prime factors of n instead of num
print(factors)
#------------------------------------------------------------------------------------
def is_prime(num): #This function returns True(1) if the number is prime else Flase(0)
if num == 2:return 1
if num%2 == 0:return 0
i = 3
while i < int(round(sqrt(num)) + 1):
if num % i == 0:return 0
i += 2
return 1
#---------------------------------------------------------------------------------------
prime_factors = []
for i in factors:
if is_prime(i):
prime_factors.append(i)
print("The prime factors of the numbers are:")
print(prime_factors)

Python - Prime check and increment

My objective of the below code is
check if entered number is a prime
if not print the next biggest prime
def primetest (num):
for c in range (2, num):
if num % c == 0:
repeattest (num) #not prime? increment number
else :
print (num,"is a prime number")
break
def repeattest (num): # check prime if not increment number by 1
for z in range (2, num):
num = num+1
primetest (num)
if num % z == 0:
num = num+1
else:
print ("Next Prime:", num+1)
break
num = int (input ("enter a number:")) # main code:
for y in range (2, num):
if num % y == 0:
repeattest (num)
else:
print (num,"is a prime number")
break
I think the logic is fine, but not sure why im not getting any output.
Time comlexity of your code is O(N) when it find a number which is prime or not.
There is no pointing on dividing from 2 to len(num)-1. It is enough to loop from 2 to sqrt of the given number. Therefore time complexity reduce to O(n) to O(log(n)).
import math
num = int (input ("enter a number:"))
def primeTest(num):
isPrime = 0
for i in range(2,int(math.sqrt(num)+1)):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print(num, "is a prime number")
else:
num = num + 1
repeatTest(num)
def repeatTest (num):
isPrime = 0
for i in range(2,int(math.sqrt(num))):
if num%i == 0:
isPrime = isPrime + 1
break
if isPrime == 0:
print("Next Prime: ", num)
else:
num = num + 1
repeatTest(num)
primeTest(num)
The logic which you are using to find if a number if prime seems wrong .
Taking a integer like 9 prints "9 is a prime number" .
And also you are checking for next prime numbers from 2 to Num .
Num being the input , you cant get a number greater than that .
It exits from the loop without even getting in , therefore not printing anything when you are searching for next prime .
You need to change the logic .
write a separate function for checking prime and end the loop when you find the next prime number instead of stopping at num .

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

Categories