目錄
- 1.題目解釋
- 2.判斷一個數是否為阿姆斯特朗數
- 2.寫一個查找固定范圍內的阿姆斯特朗數
1.題目解釋
如果一個n位正整數等于其各位數字的n次方之和,則稱該數為阿姆斯特朗數, 例如1^3 + 5^3 + 3^3 = 153,
1000以內的阿姆斯特朗數: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
2.判斷一個數是否為阿姆斯特朗數
1.先來一個簡單的代碼,判斷一個數是否為阿姆斯特朗數;
來看看C++寫的
#include <iostream>
using namespace std;
int main()
{
int n, r, sum=0, temp;
cout<<"Enter the Number= ";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
cout<<"Armstrong Number."<<endl;
else
cout<<"Not Armstrong Number."<<endl;
return 0;
}
運行結果:

接下來看看Python
num = int(input("請輸入一個數字:"))
sum= 0
n = len(str(num))
temp = num
while temp >0:
digit = temp %10 # 獲取個位數字
sum += digit**n # 對計算結果進行累加
temp //= 10
if num == sum :
print("太棒了!",num,"是阿姆斯特朗數")
else:
print("很遺憾!",num,"不是阿姆斯特朗數")
運行結果:

2.寫一個查找固定范圍內的阿姆斯特朗數
python實作:
lower = int(input("最小值:"))
upper = int(input("最大值:"))
print("下面是你想要從{}到{}之間的阿姆斯特朗數\n".format(lower,upper))
for num in range(lower,upper+1):
sum = 0
n = len(str(num))
temp = num
while temp >0:
digit = temp %10 # 獲取個位數字
sum+= digit**n # 對計算結果進行累加
temp //= 10
if num == sum:
print(num)
運行結果:

C++實作:
#include <iostream>
using namespace std;
int test(int a,int b,int c,int d)
{
if(a)return a*a*a*a+b*b*b*b*b+c*c*c*c+d*d*d*d*d;
if(b)return b*b*b+c*c*c+d*d*d;
if(c)return c*c+d*d;
if(d)return d;
}
void func(int min, int max)
{
if(min<=0||min>=max||max<0||max>9999)
{
cout << "error!" << endl;
}
int a,b,c,d;
for(int i=min;i<=max;i++)
{
a = i/1000;
b = (i%1000)/100;
c = (i%100)/10;
d = i%10;
if(i==test(a,b,c,d))
cout << i << endl;
}
}
int main()
{
int min,max;
cin >> min;
cin >> max;
func(min,max);
system("pause");
return 0;
}
運行結果展示:

C++太復雜了,就不能向python學學,多友好的語言,學C++心態炸裂的第二天,如果有幫助到你點個關注唄!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/231005.html
標籤:python
