Palindromic Primes
Solve this assignment using while loops
A palindromic number is a number that reads the same forwards and backwards. Example: "121" (You read: "one, two, one", forwards and backwards). "1001" ("one, zero, zero, one"), etc.
Write a function next_palindromic_prime
that receives a number and returns the closest larger number that's both a prime and palindromic.
As we haven't worked with strings in depth yet, we've already provided a function to reverse a string (useful for your is_palindromic
function).
Examples:
next_palindromic_prime(100) == 101
next_palindromic_prime(150) == 151
next_palindromic_prime(160) == 181
next_palindromic_prime(200) == 313
next_palindromic_prime(10000) == 10301
next_palindromic_prime(12000) == 12421
You can use the following list of Palindromic Primes as a reference: https://oeis.org/A002385.
Wikipedia also has an entry on Palindromic Primes.
Test Cases
test is prime - Run Test
def test_is_prime():
assert is_prime(2) is True
assert is_prime(3) is True
assert is_prime(13) is True
assert is_prime(17) is True
assert is_prime(97) is True
assert is_prime(331) is True
assert is_prime(2347) is True
assert is_prime(2677) is True
assert is_prime(7919) is True
test is not prime - Run Test
def test_is_not_prime():
assert is_prime(4) is False
assert is_prime(8) is False
assert is_prime(15) is False
assert is_prime(21) is False
assert is_prime(28) is False
assert is_prime(7833) is False
test next palindromic primes - Run Test
def test_next_palindromic_primes():
assert next_palindromic_prime(100) == 101
assert next_palindromic_prime(150) == 151
assert next_palindromic_prime(160) == 181
assert next_palindromic_prime(200) == 313
assert next_palindromic_prime(10000) == 10301
assert next_palindromic_prime(12000) == 12421
test is not palindromic - Run Test
def test_is_not_palindromic():
assert is_palindromic(123) is False
assert is_palindromic(321) is False
assert is_palindromic(28) is False
assert is_palindromic(81239123) is False
test is palindromic - Run Test
def test_is_palindromic():
assert is_palindromic(121) is True
assert is_palindromic(10001) is True
assert is_palindromic(10301) is True
assert is_palindromic(11311) is True
assert is_palindromic(12121) is True
assert is_palindromic(12421) is True
Solution 1
def reverse_str(s):
return s[::-1]
def is_palindromic(n):
return str(n) == reverse_str(str(n))
def is_prime(n):
if n in (2, 3):
return True
if n % 2 == 0:
return False
i = 3
while i < n-1:
if n % i == 0:
return False
i += 2
# Could have been written with a for-loop
# for simplicity:
#for i in range(3, n-1, 2):
# if n % i == 0:
# return False
return True
def next_palindromic_prime(n):
n += 1
#while not is_palindromic(n) and not is_prime(n):
while True:
if is_palindromic(n) and is_prime(n):
return n
n += 1