Reputation: 99
Non-prime numbers are being printed because it checks only from '2-10' for prime numbers. How can I change the code to check for all numbers upto x?
N = eval(input("Enter the starting point N: \n"))
M = eval(input("Enter the ending point M: \n"))
n = str(N)
i = 0
for j in range(N, M):
if (n[i] == n[len(n)-1]):
x = N
N = N + 1
if not((x % 2 == 0) or (x % 3 == 0) or (x % 4 == 0) or (x % 5 == 0) or (x % 6 == 0) or (x % 7 == 0) or (x % 8 == 0) or (x % 9 == 0) or (x % 10 == 0)):
print(x)
n = str(N)
else:
N = N + 1
n = str(N)
Upvotes: 0
Views: 1471
Reputation: 3682
Heres a palindrome snippet
low_range = input()
high_range = input()
string_convertor = str
for num in range(int(low_range), int(high_range)):
num_to_string = string_convertor(num)
reverse = num_to_string[::-1]
if num_to_string == reverse:
print("Palindrome")
print(num_to_string)
Upvotes: 0
Reputation: 6607
Here's an implementation of the Sieve of Eratosthenes that I wrote. It pretty efficiently finds all the prime numbers less than the number you pass it. I would explain it to you, but Wikipedia (linked above) does a much better job than I could. Use it to generate the prime numbers and then iterate through the list it returns to check if those numbers are palindromes.
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 range(n) if A[num]]
Upvotes: 1