如果一個數的平方的最後幾個數字給出相同的數,則稱這個數為自同構數。
以下是自同構數的例子-
1。輸入: 25
輸出- 對,是一個自同構數。
原因-25 的平方等於 625,因為最後一位是 25,所以它是一個自同構數。
2。輸入: 14
輸出- 不,不是自同構數。
原因-14 的平方等於 196,因為最後一位是 96,所以不是自同構數。
3。輸入: 76
輸出- 對,是一個自同構數。
原因-76 的平方等於 6776,因為最後一位是 76,所以它是一個自同構數。
既然這個概念現在對我們來說很清楚了,讓我們看看如何建立邏輯來檢查一個數是否是自同構的。
我們知道模數運算符可以用來對一個數的數字執行函數。
下面說明了如何在 Python 中實現。
示例-
num = int(input("Enter a number you want to check: \n"))
#calculating the number of digits
num_of_digits = len(str(num))
#computing the square of a number
square = num**2
#obtaining the last digits
last_digits = square%pow(10,num_of_digits)
#comparing the digits of number with input
if last_digits == num:
print("Yes, {} is an automorphic number".format(num))
else:
print("No, {} is not an automorphic number".format(num))
輸出
Enter a number you want to check:
76
Yes, 76 is an automorphic number
所以,讓我們來看一看相同的逐步方法-
- 第一步是從用戶那裡獲取數字並計算其平方。
- 我們可以通過使用 len 函數來計算位數。
- 接下來就是計算一個數的平方。
- 現在,我們將使用冪函數和模算子來獲得最後的數字。
- 最後,我們將最後一位數字與輸入的數字進行比較。
- 在執行程序時,將顯示所需的輸出。
讓我們看看當我們傳遞我們在示例中討論的數字時會發生什麼。
因為 25 是一個自同構數,所以它顯示所需的消息。
輸出- 2
Enter a number you want to check:
25
Yes, 25 is an automorphic number
因為 14 不是自同構數,所以它顯示所需的消息。
輸出- 3
Enter a number you want to check:
14
No, 14 is not an automorphic number
使用 While循環
下一個方法如下
示例-
print("Enter the number you want to check:")
num=int(input())
square=num*num
flag=0
while(num>0):
if(num%10!=square%10):
print("No, it is not an automorphic number.")
flag=1
break
num=num//10
square=square//10
if(flag==0):
print("Yes, it is an automorphic number.")
輸出
Enter the number you want to check:
25
Yes, it is an automorphic number.
讓我們了解我們在這個項目中遵循的步驟-
- 第一步保持不變,即從用戶處獲取數字並計算其平方。
- 我們已經聲明了一個
While循環,它將一直執行到數字變為零。 - 現在我們將比較一個數的單位位數是否等於計算平方後得到的數的單位位。
- 如果滿足上述條件,那麼我們將進行數和平方數的樓層劃分。
- 在執行程序時,它顯示該數是否是自同構數。
因此,在本文中,我們學習了什麼是自同構數,以及如何使用 Python 檢查給定的數是否是自同構的。
原創文章,作者:GLC0F,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130588.html
微信掃一掃
支付寶掃一掃