[leetcode] 866. Prime Palindrome

Description

Find the smallest prime palindrome greater than or equal to N.

Recall that a number is prime if it’s only divisors are 1 and itself, and it is greater than 1.

For example, 2,3,5,7,11 and 13 are primes.

Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.

For example, 12321 is a palindrome.

Example 1:

Input: 6
Output: 7

Example 2:

Input: 8
Output: 11

Example 3:

Input: 13
Output: 101

Note:

  • 1 <= N <= 10^8
  • The answer is guaranteed to exist and be less than 2 * 10^8.

分析

题目的意思是:给定N,找出大于N的最小回文素数。这道题我最能想到的就是暴力破解,觉得可能会超时。后面看了答案貌似也是以暴力求解,只是缩小了搜索空间。暴力破解就很简单了,从N出发一直往上找,直到找到第一个符合条件的结果为止。对于判断是否是素数,只需要判断1~sqrt(n)之间是否有整除的数就行了。

代码

class Solution:
    def isPrime(self,n):
        if(n==1):
            return False
        for i in range(2,int(n**.5)+1):
            if(n%i==0):
                return False
        return True
    def reverse(self,n):
        ans=0
        while(n):
            ans=10*ans+n%10
            n=n//10
        return ans
    
    def primePalindrome(self, N: int) -> int:
        while(True):
            if((self.reverse(N)==N) and self.isPrime(N)):
                return N
            N+=1
            if(N>10**7 and N<10**8):
                N=10**8

参考文献

回文素数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值