关于从给定的整数中解决下一个更高的素数和回文数,是否有任何建议。
这是我正在尝试的代码段,但是它有点慢,请建议您是否有我可以测试的良好算法。
#!/usr/bin/python def next_higher(n): while True: s = str(n) if not any([n % i == 0 \ for i in range(2, int(n**0.5))]) and s == s[::-1]: return n n = n + 1 print next_higher(2004) print next_higher(20)
输出:
10201 101
在启动前更新了回文代码测试。比我以前的代码快得多。我正在执行user2357112的建议。
#!/usr/bin/python def next_higher(n): while True: s = str(n) if s == s[::-1]: if not any([n % i == 0 \ for i in range(2, int(n**0.5))]): return n n = n + 1 print next_higher(2004111) print next_higher(2004) print next_higher(2004) print next_higher(20)
您可以进行很多优化:
[2] + range(3, int(n**0.5) + 1, 2)
()
[]
any
True
xrange
range
+ 1
这是具有大多数优化功能的版本,最后两个除外:
def next_higher(n): if n % 2 == 0: n = n - 1 while True: n = n + 2 s = str(n) if s == s[::-1]: if not any((n % i == 0 for i in xrange(3, int(n**0.5) + 1, 2))): return n
This should be pretty fast for your needs I believe. But you can do the last 2 optimizations to make it much more faster if you want.