Python function to check if number is prime [duplicate] - python

This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 2 years ago.
def is_prime(num):
lst = []
if num > 1:
pass
else:
return False
for number in range(0, 1000000+1):
if str(num) in str(number):
continue
elif str(1) in str(number):
continue
elif str(0) in str(number):
continue
lst.append(number)
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
print(is_prime(9))
I do not know what is the problem with my code and I cannot find a solution the point of the program is to check whether the number is a prime number or not(prime number is only divisible by 1 and itself). The for loop just doesn't seem to work or something

def isprime(n):
return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))
Output:
False
False
True
True
False
False
True
Or:
def isprime(n):
if n < 2: return False
for i in range(2, n):
if n % i == 0:
return False
else:
return True

Line 16-19:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
The first statement, num % num == 0 is finding the remainder when num is divided by num, which is always zero and therefore this statement is always true. num % 1 == 0 is also always true, so your code is equivalent to:
if not(num % x == 0):
return True
else:
return False
Which means, in the context of your program, "if the first value in lst is not a factor of num, then num is prime. Otherwise, num is not prime"
This only runs the loop one time and is backwards. Instead, you need to check if one of the numbers in lst is a factor to return False, and if all of the number is lst are not factors, then return True
for x in lst:
if num % x == 0:
return False
return True

for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
This loop can only ever run once, as it's guaranteed to return either true or false at the first iteration. If you find any factors, you want to return False. Otherwise, True.
for x in range(2, num):
if num % x == 0:
return False
return True
(Also, I'm not sure what was going on with the str shenanigans or the num % num / num % 1 conditions, both of which are always zero. But those should be unnecessary)

Except for 2 itself, you should only check divisibility by odd numbers up to the square root of the value.
Here's a short version:
def isPrime(N):
return all(N%p for p in range(3,int(N**0.5)+1,2)) if N>2 and N&1 else N==2

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

Create a list of numbers dividable by certain numbers by using the command « filter() »

I’m on Python) I have to use filter() to create a list of all numbers from 1 to 100 (inclusive) that are dividable by 7, 9 and 42. I wrote this code, however, when I start it, it does not give me the right solutions. Do you know where the problem is ?
listnumbers = []
for x in range (1, 101):
x = str(x)
listnumbers.append(x)
print (listnumbers)
def dividable(k):
for t in k:
if int(t) % 7 == 0:
return True
if int(t) % 9 == 0:
return True
if int(t) % 42 == 0:
return True
else:
return False
return dividable
s2u = list(filter(dividable, listnumbers))
for q in s2u:
print(q)
According to your problem statement the number should be divisible by 7 and 9 and 42.
listnumbers = list(range(1,101))
def dividable(k):
if k % 7 == 0 and k % 9 == 0 and k % 42 == 0:
return True
else:
return False
ans = list(filter(dividable, listnumbers))
print(ans)
Just eyeballing your code, I think dividable(k) is not written correctly. Update to :
def dividable(k):
n = int(k)
return n % 7 == 0 or n % 9 == 0 or n % 42 == 0:
Why was there a for look declared in this method? And why was it returning the function at the end if it passed through the rest of the conditions?

Python3.x Prime Number List with while loop

def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,

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

Trying to see if a number is prime in python [duplicate]

This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Closed 7 years ago.
I am trying to write a program that tells you whether a number is prime or not. Here it is. As you can see when you run the chkPrime function everything returns true. I for the life of me can't figure it out. Any ideas?
total=0
#Check if number is whole
def chkWhole(x):
if(x%1 == 0):
return True
else:
return False
#Check to see if the number divides evenly with all primes
def chkModtwo(n):
a=n%2
if chkWhole(a)==True:
return True
else:
return False
def chkModthree(n):
a=n%3
if chkWhole(a)==True:
return True
else:
return False
def chkModfive(n):
a=n%5
if chkWhole(a)==True:
return True
else:
return False
def chkModseven(n):
a=n%7
if chkWhole(a)==True:
return True
else:
return False
#Check if the number is a prime using other two functions
def chkPrime(n):
if n== 1 or 2 or 3 or 5 or 7:
return True
if chkModtwo(n)==False and chkModthree(n)==False and chkModfive(n)==False and chkModseven(n)==False:
return True
else:
return False
#while True:
#yourinput=raw_input("Enter to check if it is a prime")
#
#
# youranswer=chkPrime(yourinput)
#
# if youranswer==True:
# print("Yes, it is a prime")
# else:
# print("No, this number is not prime")
if n== 1 or 2 or 3 or 5 or 7:
should be
if n == 1 or n == 2 or n == 3 or n == 5 or n == 7:
or
if n in (1, 2, 3, 5, 7):
How does your function respond when it tries to determine if 143 is prime or composite?
Here's how I wrote this function at my blog.
def isPrime(n):
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
this will be fast and concise for numbers up to 10^14 assuming you are not going for maximum efficiency. it takes about 15 seconds to iterate through each number in the range 10**7. so you can do this execution in about 10-15 seconds for numbers of this size. of course, you can change the print statements to whatever you need them to be
Try:
import math
def isPrime(x):
prime = True
if x%2 == 0:
Prime =False
else:
for i in range(2,math.sqrt(x)):
if a == i:
pass
else:
a%i == 0:
Prime = False
break
return Prime
if isPrime(x):
print('prime')
else:
print('Not prime')
def prime():
a=int(raw_input("enter the no : "))
if a == 1:
print "the no is not prime"
elif a == 2:
print "the no is prime"
else:
for i in range(2,a):
if a%i == 0:
return "the no is not prime"
else:
return "the no is prime"
prime()

Categories