I have been trying to write a Python program which uses a recursive function to find the palindromic primes between two integers supplied as input. Example of palindromic prime: 313
I already know how to write a recursive function for palindromes, but I am struggling with this one a lot. I would appreciate any help. Thanks
recursive function for palindromes
Presumably to do the palindrome check recursively you check the outer characters:
def is_pali(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and is_pali(s[1:-1])
Now you can iterate over the numbers and see which are palindromes:
[i for i in range(n, m) if is_pali(str(i))]
Since 30000 is the limit, this works (101101 is the smallest number it gets wrong):
>>> [n for n in range(2, 500) if str(n) == str(n)[::-1] and (2**n-1)%n == 1]
[2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383]
You can of course also use the (2**n-1)%n == 1 primality test in your own recursive palindrome function that you already have.
http://en.wikipedia.org/wiki/Fermat_primality_test
Probably you already went through this idea but here's what I would do...
If you have a palindrome function like this one:
def palindrome(word):
if len(word) == 1 or (len(word) == 2 and word[0] == word[1]):
return True
else:
if word[0] == word[len(word)-1]:
return palindrome(word[1] + word[len(word)-2])
else:
return False
And let's say you have a function to figure out if a number is prime (this I take from here):
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(math.sqrt(number) + 1), 2):
if number % current == 0:
return False
return True
return False
You can just call the validation when you find out if your number is a palindrome (casting it to str first).
The missing part is generate the combination of the two integers you might get but well, that's a simple one.
Hope this helps.
-Edit:
Adding a recursive function for getting primes:
def prime(number,limit = 1):
if limit == number:
return True
else:
if number % limit == 0 and limit != 1:
return False
else:
return prime(number, limit + 1)
Instead of recursive solution, what about using more effective list slicing?
def isPalindrome(number):
nstr = str(number)
return nstr == nstr[::-1]
This works by converting the number to string and comparing it's reversed counterpart. There is also known algorithm for determining the palindrome,
using global variable:
sum = 0
def is_palindrome(number):
return palindrome_sum(number) == number
def palindrome_sum(number):
global sum
if number != 0:
remainder = number % 10
sum = sum * 10 + remainder
palindrome_sum(number / 10) * 10 + remainder
return sum
For mathematical recursive function without global variable, this algorithm can be used:
import math
def is_palindrome(number):
return palindrome_sum(number) == number
def palindrome_sum(number, sum=0):
iters = 0
if number != 0:
iters = int(math.log10(number))
remainder = number % 10
sum = palindrome_sum(number / 10) + remainder * 10 ** iters
return sum
It uses the length of number to find it's position in the resulting number. The length can be computed by int(math.log10(number)).
This solution uses the Sieve of Eratosthenes to find the prime numbers less than n. It then uses a basic palindrome check which of those prime numbers are palindromes. The check avoids converting the ints to strs, which is a time consuming operation.
#!/usr/bin/env python2.7
def primeslt(n):
"""Finds all primes less than n"""
if n < 3:
return []
A = [True] * n
A[0], A[1] = False, False
for i in range(2, int(n**0.5)+1):
if A[i]:
j = i**2
while j < n:
A[j] = False
j += i
return (num for num in xrange(n) if A[num])
def is_palindrome(n):
digits = []
while n > 0:
digits.append(n%10)
n /= 10
return digits == digits[::-1]
def main():
while True:
try:
i = int(raw_input("Palindromic primes less than... "))
break
except ValueError:
print "Input must be an integer."
print filter(is_palindrome, primeslt(i))
if __name__ == '__main__':
main()
If you have any questions about how this code works, feel free to ask me by commenting on my answer. Best of luck!
Related
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,
I am trying to create a program in python that takes a number and determines whether or not that number is prime, and if it is prime I need it to list all of the prime numbers before it. What is wrong with my code?
import math
def factor(n):
num=[]
for x in range(2,(n+1)):
i=2
while i<=n-1:
if n % i == 0:
break
i = i + 1
if i > abs(n-1):
num.append(n)
print(n,"is prime",num)
else:
print(i,"times",n//i,"equals",n)
return
Your method only returns whether the 'n' is prime or not.
For this purpose, you don't need a nested loop. Just like this
def factor(n):
num=[]
for x in range(2,(n+1)):
if n % x == 0:
break
if x > abs(n-1):
num.append(n)
print(n,"is prime",num)
else:
print(x,"times",n//x,"equals",n)
return
And then, if you want all the other primes less than n, you can use prime number sieve algorithm.
--------- Update --------------
A modification of your code which can find the other primes (but prime sieve algorithm still has better performance than this)
def factor(n):
num=[]
for x in range(2,(n+1)):
i=2
while i<=x-1:
if x % i == 0:
break
i = i + 1
if i > abs(x-1):
num.append(x)
if n in num:
print num
else:
print str(n) + ' is not num'
return
I wrote a code in python to find the nth prime number.
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
while mod < (num - 1):
ptrue = 'true'
if num%(num-mod) == 0:
ptrue = 'false'
break
mod += 1
if ptrue == 'true':
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)
The code looked fine to me, but it returns an error when I run it:
Traceback (most recent call last):
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
print(prime(nth))
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
if ptrue == 'true':
UnboundLocalError: local variable 'ptrue' referenced before assignment
It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?
how about using Boolean ? and initalize ptrue out of while loop
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
ptrue = True
while mod < (num - 1):
if num%(num-mod) == 0:
ptrue = False
break
mod += 1
if ptrue == True:
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print prime(nth)
ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop
Get rid of ptrue entirely and use else with your inner loop. For example:
while mod < (num - 1):
if num % (num - mod) == 0:
break
mod += 1
else:
primes += 1 # only executes if loop terminates normally, without `break`
You can try this:
#This program finds nth prime number
import math
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return False
else:
for i in range(3, number):
if not number % i:
return False
return True
n = input('Enter n: ')
#This array stores all the prime numbers found till n
primes = []
for i in range(100000):
if is_prime(i):
primes.append(i)
if len(primes) == n:
break
print("nth prime number is: " + str(primes[n-1]))
The first part is define a function that calculates the next prime number given any number.
import math
def is_prime(x): # function
for i in range(2,int(math.sqrt(x))+1):
if x%i == 0:
return is_prime(x+1)
return x
For example, is_prime(10) will return 11.
The next step is to write a generator that returns a list of prime numbers.
def get_prime(k): # generator
cnt = 1
n = 2
while cnt <= k:
yield(is_prime(n))
n = is_prime(n) + 1
cnt += 1
For example, get_prime(5) will return [2,3,5,7,11].
The code below can help you test the results.
a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))
All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....
def isprime(n): # First the primality test
if n<2:
return False
for i in range(2,n):
if n%i==0:
return False
break
else:
return True
def nthprime(n): # then generic code for nth prime number
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
print(x[n-1])
n=int(input('enter n'))
a=[2,3,5,7]
i=3
j=9
while i<n:
flag=0
j=j+2
for k in range(len(a)):
if (a[k]<=int(j**0.5) and j%a[k]==0):
flag=1
break
if flag==0:
a=a+[j]
i=i+1
print(a[n-1])
Try this.
n = int(input())
count=1
u=2
prime=[]
while(count<=n):
temp=0
for i in range(2,u):
if(u%i==0):
temp=1
if(temp==0):
count+=1
prime.append(u)
u+=1
print(prime[-1])
Program to find nth Prime Number.
def nth_Prime(num):
Semi = num*num
Res_1 = [True for i in range(Semi+1)]
prime = 2
while prime*prime <= Semi:
if Res_1[prime] == True:
for i in range(prime*prime, Semi+1, prime):
Res_1[i] = False
prime += 1
Res_2 = []
for i in range(2, Semi+1):
if Res_1[i]:
Res_2.append(i)
return Res_2[num-1]
if __name__ == "__main__":
num = int(input("Enter nth Number: "))
print(nth_Prime(num))
Try this out ,I just made few changes in yours.
Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.
n=raw_input("enter the nth prime ")
num=4
p=2
while p <int(n):
if all(num%i!=0 for i in range(2,num)):
p=p+1
num=num+1
print "nTH prime number: ",num-1
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
So I'm doing Project Euler because dear gods do I need to practice writing code, and also my math skills are rusty as something very rusty. Thusly; Project Euler. I'm sure most here have already seen or heard of the problem, but I'll put it here just for completeness:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
For this, I've written two functions:
from math import sqrt
def isprime(n):
if n == 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
for x in range(3, round(sqrt(n))+1, 2):
if n % x == 0:
return False
else:
return True
This just checks any fed number for primality. It's working as intended (as far as I know), but now that I've said that I grow unsure. Anyway, it checks for special cases first: 1 (never prime), 2 (prime) or if it's divisible by 2 (not prime). If none of the special cases happen, it runs a general primality test.
This is my factorization code:
def factorization(n):
factor = 2
x = 3
while True:
if n % x == 0:
if isprime(x):
factor = x
n = n // x
if n == 1:
return factor
else:
return factor
x += 2
And this is definitely not working as intended. It is, sadly, working for the particular value of the Project Euler problem, but it doesn't work for, say, 100. I'm unsure what I need to do to fix this: what happens is that if it's a number like 100, it will correctly find the first 5 (2*2*5), but after that will loop around and set x = 7, which will make the entire thing loop infinitely because the answer is 2*2*5*5. Would recursion help here? I tried it, but it didn't get any prettier (it would still go into an endless loop for some numbers). I'm unsure how to solve this now.
You're on a good track, but you need to take account of the possibility of repeating factors. You can do that with something like this:
factors = []
while num % 2 == 0:
factors.append(2)
num /= 2
The idea here being that you're going to continue adding 2's to the factor list until the number you're testing becomes odd. You can use similar logic for other factors as well to enhance your factorization method.
I think you have made the problem more complicated than necessary
Here is some pseudo code that you should be able to turn into Python code
from itertools import count
n=600851475143
for x in count(2):
while x divides n:
divide n by x
if n==1:
print x # largest factor will be the last one
break
For the repeating (odd) factors, just increment x when a divisor has not been found:
def factorization(n):
factor = 2
x = 3
while True:
if n % x == 0:
if isprime(x):
factor = x
n = n // x
if n == 1:
return factor
else:
return factor
else:
x += 2
OTOS, it seems that you miss always the "2" factors. Stick them on top and then do the main loop
EDIT (after comment)
You can do a much simpler:
def factorization(n):
factors = []
x = 2
while True:
while n % x == 0:
factors.push(x)
n /= x
if n == 1:
return factors
if x == 2:
x = 3
else:
x += 2
Here is another optimized solution:
import math
def find_prime(num):
if num <= 1:
return False
elif(num == 2):
return True
elif( num % 2 == 0):
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num%i == 0:
return False
return True
def prime_factor(number):
pf = number;
divList = [];
for i in range(2, int(math.sqrt(number))):
if number % i == 0 :
divList.append(i)
for n in divList:
if(find_prime(n)):
pf = n;
return pf
num = 600851475143
print("Max prime factor :", prime_factor(num))