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
Related
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
I have to find the largest prime factor of the number 600851475143.
The answer is 6857 but I keep getting 486847. What is the bug in my code?
def f(n):
factors = []
for i in range(1, int(math.sqrt(n))+1): #check if it is a factor
if n%i == 0:
x = True
for j in range(1, int(math.sqrt(i))+1): #check if factor is prime
if i%j == 0:
x = False
x = True
if x:
factors.append(i)
return max(factors)
print(f(600851475143))
fixed it
import math
def f(n):
factors = []
for i in range(1, int(math.sqrt(n))+1): #check if it is a factor
if n%i == 0:
x = True
for j in range(2, int(math.sqrt(i))+1): #check if factor is prime
if i%j == 0:
x = False
break
x = True
if x:
factors.append(i)
return max(factors)
print(f(600851475143))
two issues
for checking primality start from 2, as 1 will divide everything
break after you have set x as false otherwise you will set it true again and keep appending everything to the list
My code is supposed to find the first 100 of the p1*p2...*pn+1 sequence and then test if they are prime.
primes = [2,3]
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def firstNPrimes(n) :
a = 4
while len(primes) < n :
isItPrime(a)
a += 1
print(primes)
def multiplyList(q) :
result = 1
for x in q:
result = result * x
return result
h = 1
while h < 100 :
w = 2
firstNPrimes(w)
result = multiplyList(primes)
float(result)
result += 1
print(result)
w += 1
print(w)
h += 1
I don't get any errors but my code doesn't work. I think w either doesn't go up or it goes up and the program doesn't use it. When I print w after I make it go up, it goes up but the next time the program runs it doesn't use the new number.
If I understood the task, it is required to generated prime according to the Euclid's proof of Euclid's theorem from all primes between 2 and N and then print all generated primes for intervals where N goes from 2 to 100. I assume 100 is included, though it's not important.
Let's define a function is_prime(n) which return True or False. To check weather a number is prime you can check that the number is not divisible by any number from 2 to square root of the number. You might ask why square root? Because if A*B = N and if A is smaller than square root of N then B will be bigger then square root of N and we don't need to check B if we have already checked A. Let's use ceil(sqrt(N)) which returns the smallest integer value that is bigger than or equal to a number.
get_prime_range(n) generates all primes from 2 to n where n is included
generate_prime(primes) computes prime_1*prime_2* ... *prime_k + 1 which is also a prime number.
from math import sqrt, ceil
def is_prime(n):
for i in range(2, math.ceil(math.sqrt(n))):
if n % i == 0:
return False
return True
def get_prime_range(n):
primes = []
for i in range(2, n+1):
if is_prime(i):
primes.append(i)
return primes
def generate_prime(primes):
new_prime = 1 if primes else None
for prime in primes:
new_prime *= prime
return new_prime + 1
for n in range(2, 101):
print(generate_prime(get_prime_range(n)))
After tinkering with & adjusting your code, I think the following works:
def isItPrime(n):
tests = primes.copy()
while len(tests) != 0:
if n % tests[-1] == 0:
return False
elif n % tests[-1] != 0:
tests.pop()
if len(tests) == 0:
primes.append(n)
return True
def firstNPrimes(n, a=5) :
while len(primes) < n :
isItPrime(a)
a += 1
def multiplyList(q, result=1):
for x in q:
result *= x
return result
primes = [2,3]
w, h, n_iter = 2, 1, 100
while h < n_iter :
print("{}/{}".format(h,n_iter)) # To see progress
firstNPrimes(w)
result = multiplyList(primes)
float(result)
result += 1
w += 1
h += 1
print("Primes: {}".format(primes))
print("Product of the primes: {}".format(result))
Let me know if this is not what you expect.
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,
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()