I've worked a lot on this but I can't figure out the problem. Can you help me? The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) "Prime")
else:
print(str(i))
i = 1
printPrimes(100)
CodePudding user response:
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) 1, 2):
if n % i == 0:
return False
return True
CodePudding user response:
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True