why is 3 not prime number? - python

Function to identify is n prime or not.
def test_prime(n):
if n == 1:
return False
elif n==2:
return True
else:
for e in range(2,n): # iteration from 2 to n
if e % 2 == 0:
return False
return True
Why is 3 not prime number here?
print(test_prime(3))

That is because the logic you have implemented is wrong. As it is already pointed out, your code currently is checking whether or not your input number is even or odd. For checking if the number is prime, you can do as follows:
def test_prime(n):
if n == 1:
return False
elif n==2:
return True
else:
for e in range(2,n): # iteration from 2 to n
if n % e == 0:
return False
return True
The else condition will check whether the remainder after dividing the input number by each number in range is 0 or not. If it's 0 then it's not a prime number. Also, you could run the loop from 0 to half of n, which is more efficient as suggested.

Number 3 is not prime number because of the logic in the code which goes from range(2,n), what will return number 2 and 2%2 == 0 which is False.

Related

I'm trying to print the integers from 0 to 100 and identify the prime numbers

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)
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
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

How do I break an infinite Python loop?

I'm looking to fix the following code, so that it can finish successfully for all numbers listed. How can I break the infinite loop that's present?
Furthermore, how can I return print(is_power_of_two(8)) as True?
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
your while condition should be :
# Check if the number can be divided by two without a remainder
while n % 2 == 0 and n >1:
n = n / 2
cause for the moment your code infinitely loops when n=1 cause 1%2 = 1
Add and n != 0 to the while condition, so the loop will halt when n is zero.
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n!=0 and (n % 2 == 0 or 2%n==0):
n = n / 2
return True
return False
import math
math.log2(number).is_integer()
Use this. From Check if a given number is power of two in Python
def is_power_of_two(n):
#Check Number for Zero
if n==0:
return False
else:
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0 and n!=0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Can't define 2 as prime number or not

I'm trying to define prime numbers, but my algorithm doesn't recognize 2 as a prime number. Instead return None. I try it in Google Colab, Jupiter Notebook and PyCharm with same result.
My code:
# V1) Test all divisors from 2 through n-1. (skip 1 and n)
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
# ===== Test Function =====
for n in range(1, 21):
print(n, is_prime_v1(n))
My output:
1 False
2 None
3 True
4 False
5 True
6 False
7 True
8 False
9 True
10 False
11 True
12 False
13 True
14 False
15 True
16 False
17 True
18 False
19 True
20 False
Additionally, the return has some erros, like 9 is not a prime number.
This code is from, starting in 0:46: Python and Prime Numbers || Python Tutorial || Learn Python Programming
Because Your program never enters the loop.
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
starts from 2, up until n-1.
Also, you should indent it differently. Only after your program exited the loop should you return True:
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
But if you want to optimize your function, it should be like this:
def is_prime_v1(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for d in range(3, round(n**0.5) + 1, 2):
if n % d == 0:
return False
return True
Since you dont need to check up to the number itself, only it's square root.
Also, no number that is even can ever be prime (except 2), since it would be divisible by two.
EDIT:
I'm happy my answer helped :)
You can explicitly define 2 as prime.
The return True is inside your for loop and so is returning true after just 1 iteration (which is why you have errors).
For primes, it suffices to check only up to the square root of the number you are testing, this should speed things up considerably for large n.
Try this
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
elif n == 2:
return True
for d in range(2, int(n**0.5) + 1):
if n % d == 0:
return False # Is not prime
return True
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
Create a separate if for it like you did for 1.
if n == 2:
return True #2 is prime

Incorrect boolean checking for Prime

Why does the following code return True when it should return False. Trying to test if number is prime.
The intent of the code is to loop the this range(2,n) and if any number i divides n (remainder is 0) return False. The code returns True (incorrect) for 25 but False (correct) for 20. When the loop reaches 5 then 25%5 is 0 so it should return False. Where did I go wrong. There are other ways to check if number is prime but I want to know why this way does not work for 25 but does for 20.
def isPrime(n):
"""
"""
for i in range(2,n):
if n%i == 0:
return False
else:
return True
def main():
print isPrime(25) #Should return False
if __name__ == '__main__':
main()
Here is another implementation without the return statements that get so the area of the code that I would like to better understand.
for i in range(2,n+1):
if n%i == 0:
print 'for i =',i,'n%i =',n%i,'Therefore',n,'is not a prime'
print 'Should break out of loop here and return False'
else:
print 'for i =',i,'n%i =',n%i
Here is sample output.
for i = 2 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 3 n%i = 1
for i = 4 n%i = 2
for i = 5 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 6 n%i = 4
for i = 7 n%i = 3
for i = 8 n%i = 2
for i = 9 n%i = 1
So, shouldn't have broken out where i is 2 or when i is 5 when n is 10? Why doesn't it?
In your code you are checking with each number in that range and at the same time you are returning true or false, that's a bad idea. you have to return false if all the numbers in that range not matching with your condition. Instead of that in your coding you are checking for each element.
def isPrime(n):
"""
"""
for i in range(2, n):
if n % i == 0:
return False
else:
return True
print isPrime(25)
So if you write the else with for loop it will first execute for all the elements in range if nothing is matching it will it will go to the else part rather than checking if:..Else:.. for each element in that range.

Max Prime Palindrome in Python

I'm trying to create a program that outputs the highest prime number than is a palindrome and is less than 1000. Expected output should be 929
Attempt 1
number = 1
prime = 1
maxNumber = 1000
while number > maxNumber:
if str(number) == str(number)[::-1]: #Inverts the string
for number in range(number,maxNumber): #Increments number until 1000
for i in range(2, number): #Checks current number and divides all lower
if number % i == 0:
break
else:
prime = number
print(prime)
Attempt 2
number = 3
prime = 3
maxNumber = 1000
while number < maxNumber:
if str(number) == str(number)[::-1]: #Inverts the string
for i in range(2, number):
if number % i == 0:
break
else:
prime = number
number+=1
print(prime)
Attempt 3, I followed the suggestions to separate the two functions to decrease processing time
for number in xrange(1000):
if str(number) == str(number)[::-1]: and is_prime(number):
prime = number
print(number)
#Method to find prime numbers
def is_prime(n):
if n == 2 or n == 3:
return True
elif n < 2 or n%2 == 0:
return False
elif n < 9:
return True
elif n%3 == 0:
return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0:
return False
if n%(f+2) == 0:
return False
f +=6
return True
Attempt 4: Receiving the error [name 'is_prime' is not defined]
for number in range(1000,3,-1):
if str(number) == str(number)[::-1] and is_prime(number):
print(number)
break
#Method to check if number is prime
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
Final Solution: Thank you all for your help. This has been more helpful than I have ever expected.
#Method to check if number is prime
def is_prime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n%f == 0: return False
if n%(f+2) == 0: return False
f +=6
return True
#Checking for numbers that are palindromes and prime
for number in range(1000,3,-1):
if str(number) == str(number)[::-1] and is_prime(number):
print(number)
break
There are several issues with your code:
First version, your logic for the while loop is backward
Second version, your indentation is wrong. number+=1 is part of the if block above and the print is not part of the while loop.
The print at the end of the while loop is print the wrong value since it has dropped out of the loop at this point for the test while number < maxNumber:.
Try:
for n in xrange(1000):
if str(n)==str(n)[::-1] and is_prime(n):
print n
Which you can turn into a while loop easily:
n=0
while n<1000:
if str(n)==str(n)[::-1] and is_prime(n):
print n
n+=1
I suggest separating out the prime testing from the palindrome testing. Since testing a string for being a palindrome is fast in comparison to testing if a number is a prime (for larger numbers) test for a palindrome first.
There is a function for testing a number as being a prime here.
Based on your comments, I now see you are looking for the max and not all of the prime palindromes.
To get the max prime palindrome, you can just step backwards from the max value. Since you do not know if that max value is prime or not or even or not, you need to step by -1 (or write some additional code that confuses the concept):
for number in range(1000,3,-1):
if str(number) == str(number)[::-1] and is_prime(number):
print(number)
break
Which you can make 'Pythonic' by just using next and a generator:
>>> next(n for n in range(1000,3,-1) if str(n)==str(n)[::-1] and is_prime(n))
929
Or, use max with a list of the primes (way less efficient since you have to generate them all):
>>> max(n for n in range(1000) if str(n)==str(n)[::-1] and is_prime(n))
929

Categories