In mathematics, a Kaprekar number for a given base is a non-negative integer, the representation of whose square in that base can be split into two parts that add up to the original number again. For instance, 45 is a Kaprekar number, because 45² = 2025 and 20+25 = 45.
I want to print all Kaprekar numbers between two integers p and q
def kaprekarNumbers(p, q):
for i in range(int(p),int(q)):
square = str(i ** 2)
if len(square) % 2 == 0:
p1 , p2 = square[:len(square)/2] , square[len(square)/2:]
else:
p1 , p2 = square[:int(len(square)/2)] , square[int(len(square)/2) :]
if int(p1) + int(p2) == int(i):
print(i , end = '')
错误: 编译器消息:
Runtime Error
Error(stderr) :
Traceback (most recent call last):
File "solution.py", line 26, in <module>
kaprekarNumbers(p, q)
File "solution.py", line 17, in kaprekarNumbers
if int(p1) + int(p2) == int(i):
ValueError: invalid literal for int() with base 10: ''
感谢您的帮助。你知道吗
如果
p
是[0,3]范围内的整数,因此它的平方是一个单位数整数,那么您对平方字符串版本的拆分将为p1
生成一个空字符串。int(“”)是一个错误。在尝试转换之前,必须检查该值:更好的方法是,覆盖一位数大小写,这样您就可以选择
1
作为有效数字:下面是一个更高级的实现(当您更熟悉Python时)。你知道吗
代码.py:
注意事项:
kaprekar
函数:splitter
(向右->;向左)保持,这两部分用[Python]: divmod(a, b)计算输出:
相关问题 更多 >
编程相关推荐