如何使用Python查找给定范围内的Kaprekar数字?
修改后的Kaprekar数是带有d位的正整数n,因此当我们将其平方分为两部分时-右手r为d位,左手为l包含剩余的d或d-1位,总和等于原始数(即l + r = n)。
您可以通过测试给定范围内给定条件的每个数字来找到给定范围内的Kaprekar数。
示例
def print_Kaprekar_nums(start, end):for i in range(start, end + 1):
# Get the digits from the square in a list:
sqr = i ** 2
digits = str(sqr)
# Now loop from 1 to length of the number - 1, sum both sides and check
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == i:
print("Number: " + str(i) + "Left: " + str(left) + " Right: " + str(right))
print_Kaprekar_nums(150, 8000)
输出结果
这将给出输出-
Number: 297Left: 88 Right: 209Number: 703Left: 494 Right: 209
Number: 999Left: 998 Right: 1
Number: 1000Left: 1000 Right: 0
Number: 2223Left: 494 Right: 1729
Number: 2728Left: 744 Right: 1984
Number: 4879Left: 238 Right: 4641
Number: 4950Left: 2450 Right: 2500
Number: 5050Left: 2550 Right: 2500
Number: 5292Left: 28 Right: 5264
Number: 7272Left: 5288 Right: 1984
Number: 7777Left: 6048 Right: 1729
以上是 如何使用Python查找给定范围内的Kaprekar数字? 的全部内容, 来源链接: utcz.com/z/322094.html