table of Contents
1. Title explanation
If an n-digit positive integer is equal to the sum of the n-th power of its digits, the number is called an Armstrong number. For example, 1^3 + 5^3 + 3^3 = 153 .
Armstrong numbers within 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
2. Determine whether a number is an Armstrong number
1. First come with a simple code to determine whether a number is an Armstrong number ;
let’s take a look at the code written in 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;
}
operation result:
Next look at 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,"不是阿姆斯特朗数")
operation result:
2. Write a search for Armstrong numbers in a fixed range
Python implementation:
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)
Running results:
C++ implementation:
#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;
}
Run results show:
C++ is too complicated to learn from python. What a friendly language, the second day after the burst of learning C++ mentality, if it helps, please pay attention to it!