Writing A Function That Checks Prime Numbers
def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False break else: return True
Solution 1:
The problem with your code is that you have return
statements in the first iteration of the loop. Also break
statement is not needed. Moving return True
outside the loop gives the solution:
defprimecheck(num):
for i inrange(2, num):
if num % i == 0:
returnFalsereturnTrue
I leave num
= 0 or 1 for you.
Solution 2:
Or you can simply use for else for this.
defprimecheck(num):
if num>1:
for i inrange(2, num):
if num%i==0:
returnFalsebreakelse:
returnTrueprint(primecheck(15))
Solution 3:
The problem is with your else
statement, no need for it. And also break
is not needed
defprimecheck(num):
if num > 1:
for i inrange(2, num):
if (num % i) == 0:
returnFalsereturnTrue
or you can solve it without any iterations. You can use Fermat's little theorem to solve this easily(hope you refer it),
defprimeChecker(n):
m = 2#can be any numberif(n > 1):
if (((m**n)-m)%n == 0): #Using Fermat's little theoremreturnTruereturnFalse
n = int(input());
if primeChecker(n):
print('{} - is prime number'.format(n))
else:
print('{} - NOT a prime number'.format(n))
Doing a little research on the internet will help to solve these types of questions much easier and efficiently. ;). Cheers!
Solution 4:
You are using return in the else part. So your code will break after 1st iteration and print the result of first iteration.
You can do something like this:
defprimecheck(num):
if num > 1:
for i inrange(2, num):
if (num % i) == 0:
returnFalsereturnTrueprint(primecheck(15))
Post a Comment for "Writing A Function That Checks Prime Numbers"