如何使用 Python 在給定範圍內找到卡普里卡數?
改進後的卡普里卡數是指正整數n,其中含有d位數字,當我們將它的平方拆成兩部分——右邊部分r含有d位數字,左邊部分l包含剩餘的d或d-1位數字——部分的和等於原始數(即l+r=n)。
可以透過在給定範圍內測試每個數是否滿足給定的條件,從而在給定範圍內找到卡普里卡數。
示例
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: 209 Number: 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
廣告