Home > other >  Get nth Prime and Palindrome number
Get nth Prime and Palindrome number

Time:12-24

def ispalindrome(number):
    x=number
    reverse=0
    while(x!=0):
        digit=x
        reverse=reverse*10 digit
        x=x//10
    if number==reverse:
        return True
    else:
        return False
def isprime(num):
    y=True
    for i in range(2,num):
        if(num%i==0):
            y= False
            break
    return y
n=int(input("Enter the value of n:"))
primeAndPalindrome=[]
p=10**n
for j in range (2,p):
    if ispalindrome(j) and isprime(j):
        primeAndPalindrome.append(j)
    if len(primeAndPalindrome)==n 10:
        break
print(f'{n}th Prime Palindrome number is {primeAndPalindrome[n-1]}')

if len(primeAndPalindrome)==n 10:

what is use of this line , if I don't use this my code runs but the execution takes much time.

Can someone explain the use of this line.

CodePudding user response:

You are checking the nth prime and palindrome in a range of numbers from 2 to 10**n. The bigger n input is the bigger your list and the more time it will take to execute. if len(primeAndPalindrome)==n 10: limits your list size to n 10 only so it seems faster but the problem is still your program cannot handle big numbers.

Also, your checking functions (isPalindrome and isPrime) could be improved a lot.

CodePudding user response:

As @Florian EDEMESSI says the approach needs improving so here are re-coded check functions to start with:

def ispalindrome(number):
    x=str(number)
    return x == x[::-1]


def isprime(num):
    if num <= 1:
        return False
    for i in range(2,int(num**0.5)):
        if(num%i==0):
            return False
    return True
  • Related