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
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.
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
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
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 have been trying to write a program that will take an imputed number, and check and see if it is a prime number. The code that I have made so far works perfectly if the number is in fact a prime number. If the number is not a prime number it acts strange. I was wondering if anyone could tell me what the issue is with the code.
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
a=a+1
else:
print('prime')
a=(num)+1
The result given when 24 is imputed is:
not prime
not prime
not prime
prime
How would I fix the error with the reporting prime on every odd and not prime for every even?
You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.
Making only minimal changes to your code to make it work:
a=2
num=13
while num > a :
if num%a==0 & a!=num:
print('not prime')
break
i += 1
else: # loop not exited via break
print('prime')
Your algorithm is equivalent to:
for a in range(a, num):
if a % num == 0:
print('not prime')
break
else: # loop not exited via break
print('prime')
If you throw it into a function you can dispense with break and for-else:
def is_prime(n):
for i in range(3, n):
if n % i == 0:
return False
return True
Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.
With these suggestions:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
Note that this code does not properly handle 0, 1, and negative numbers.
We make this simpler by using all with a generator expression to replace the for-loop.
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
Taken from:
http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python
def is_prime(n):
return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1
The two main problems with your code are:
After designating a number not prime, you continue to check the rest of the divisors even though you already know it is not prime, which can lead to it printing "prime" after printing "not prime". Hint: use the `break' statement.
You designate a number prime before you have checked all the divisors you need to check, because you are printing "prime" inside the loop. So you get "prime" multiple times, once for each divisor that doesn't go evenly into the number being tested. Hint: use an else clause with the loop to print "prime" only if the loop exits without breaking.
A couple pretty significant inefficiencies:
You should keep track of the numbers you have already found that are prime and only divide by those. Why divide by 4 when you have already divided by 2? If a number is divisible by 4 it is also divisible by 2, so you would have already caught it and there is no need to divide by 4.
You need only to test up to the square root of the number being tested because any factor larger than that would need to be multiplied with a number smaller than that, and that would already have been tested by the time you get to the larger one.
This example is use reduce(), but slow it:
def makepnl(pnl, n):
for p in pnl:
if n % p == 0:
return pnl
pnl.append(n)
return pnl
def isprime(n):
return True if n == reduce(makepnl, range(3, n + 1, 2), [2])[-1] else False
for i in range(20):
print i, isprime(i)
It use Sieve Of Atkin, faster than above:
def atkin(limit):
if limit > 2:
yield 2
if limit > 3:
yield 3
import math
is_prime = [False] * (limit + 1)
for x in range(1,int(math.sqrt(limit))+1):
for y in range(1,int(math.sqrt(limit))+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(math.sqrt(limit))):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
for n in range(5,limit):
if is_prime[n]: yield n
def isprime(n):
r = list(atkin(n+1))
if not r: return False
return True if n == r[-1] else False
for i in range(20):
print i, isprime(i)
Your problem is that the loop continues to run even thought you've "made up your mind" already. You should add the line break after a=a+1
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
Begginer here, so please let me know if I am way of, but I'd do it like this:
def prime(n):
count = 0
for i in range(1, (n+1)):
if n % i == 0:
count += 1
if count > 2:
print "Not a prime"
else:
print "A prime"
This would do the job:
number=int(raw_input("Enter a number to see if its prime:"))
if number <= 1:
print "number is not prime"
else:
a=2
check = True
while a != number:
if number%a == 0:
print "Number is not prime"
check = False
break
a+=1
if check == True:
print "Number is prime"
a=input("Enter number:")
def isprime():
total=0
factors=(1,a)# The only factors of a number
pfactors=range(1,a+1) #considering all possible factors
if a==1 or a==0:# One and Zero are not prime numbers
print "%d is NOT prime"%a
elif a==2: # Two is the only even prime number
print "%d is prime"%a
elif a%2==0:#Any even number is not prime except two
print "%d is NOT prime"%a
else:#a number is prime if its multiples are 1 and itself
#The sum of the number that return zero moduli should be equal to the "only" factors
for number in pfactors:
if (a%number)==0:
total+=number
if total!=sum(factors):
print "%d is NOT prime"%a
else:
print "%d is prime"%a
isprime()
This is a slight variation in that it keeps track of the factors.
def prime(a):
list=[]
x=2
b=True
while x<a:
if a%x==0:
b=False
list.append(x)
x+=1
if b==False:
print "Not Prime"
print list
else:
print "Prime"
max=int(input("Find primes upto what numbers?"))
primeList=[]
for x in range(2,max+1):
isPrime=True
for y in range(2,int(x**0.5)+1) :
if x%y==0:
isPrime=False
break
if isPrime:
primeList.append(x)
print(primeList)
Prime number check.
def is_prime(x):
if x < 2:
return False
else:
if x == 2:
return True
else:
for i in range(2, x):
if x % i == 0:
return False
return True
x = int(raw_input("enter a prime number"))
print is_prime(x)
# is digit prime? we will see (Coder: Chikak)
def is_prime(x):
flag = False
if x < 2:
return False
else:
for count in range(2, x):
if x % count == 0:
flag = True
break
if flag == True:
return False
return True