#this function checks if a number is a prime number,
#if not it outputs the lowest factor.
def isprime(n):
"""Determines whether a number is a Prime number,
Takes a single arguement n, which is the number"""
if n==1:
return 'Not a Prime number, only has one distinct factor'
elif n==2:
return 'Prime number'
elif n==3:
return 'Prime number'
else:
for i in range(2,n):
if n%i==0:
return 'Not a prime number',i,'is a factor'
else:
return 'Prime number'
#example
#print(isprime(590))
#outputs
#>>>
#('Not a prime number', 2, 'is a factor')
#Adegoke Obasa ----adegokeobasa@yahoo.com----
e-papa
13
Posting Pro in Training
Recommended Answers
Jump to PostAnother speedup: You only need to check for factors up to the square root of the target.
Jump to PostAnd please do a reasonable number of tests of your code before posting. This is a truncated version of the function to point out the error:
def isprime(n): for ctr in range(2,n): ## do not use 'i', 'l', 'O' as they can look like numbers if n%ctr==0: …
Jump to PostHere is what could be considered 'behind the book correct answer' cheat to is_prime function from my utility module:
def is_prime(n): sqrt_n = int(n**0.5 + 0.5) if n == 2 or n == 3: return True elif n < 2 or n % 2 == 0 or …
All 10 Replies
vegaseat
1,735
DaniWeb's Hypocrite
Team Colleague
griswolf
304
Veteran Poster
e-papa
commented:
Speed is key, your comment is sure fast.
+1
e-papa
13
Posting Pro in Training
woooee
814
Nearly a Posting Maven
e-papa
13
Posting Pro in Training
TrustyTony
888
pyMod
Team Colleague
Featured Poster
e-papa
commented:
You are great.
+1
e-papa
13
Posting Pro in Training
woooee
814
Nearly a Posting Maven
e-papa
13
Posting Pro in Training
e-papa
13
Posting Pro in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.