Reputation: 35
I'm trying to create a python program to check if a given number "n" is prime or not. I've first created a program that lists the divisors of n:
import math
def factors(n):
i = 2
factlist = []
while i <= n:
if n% i == 0:
factlist.append(i)
i = i + 1
return factlist
factors(100)
Next, I'm trying to use the "for i in" function to say that if p1 (the list of factors of n) only includes n itself, then print TRUE, and if else, print FALSE. This seems really easy, but I cannot get it to work. This is what I've done so far:
def isPrime(n):
p1 = factors(n)
for i in p1:
if factors(n) == int(i):
return True
return False
Any help is appreciated! This is a hw assignment, so it's required to use the list of factors in our prime test. Thanks in advance!
Upvotes: 0
Views: 46
Reputation: 7404
p1
will only have n
if if has length 1. It may be worthwhile to add if len(p1)==1
as the conditional instead.
Upvotes: 1
Reputation: 738
I usually do something like this:
primes = [2,3]
def is_prime(num):
if num>primes[-1]:
for i in range(primes[-1]+2, num+1,2):
if all(i%p for p in primes):
primes.append(i)
return num in primes
This method generates a global list of prime numbers as it goes. It uses that list to find other prime numbers. The advantage of this method is fewer calculations the program has to make, especially when there are many repeated calls to the is_prime function for possible prime numbers that are less than the largest number you have previously sent to it. You can adapt some of the concepts in this function for your HW.
Upvotes: 0
Reputation: 1611
What I did (I actually managed to get it in 1 line) was use [number for number in range (2, num // 2) if num % number == 0]
. This gets all the numbers that are factors of num
. Then you can check if the length of that list is > 0
. (Wouldn't be prime).
Upvotes: 0