1. Explanation of the topic
An n-digit positive integer is said to be an Armstrong number if it is equal to the sum of the nth power of its digits. For example1^3 + 5^3 + 3^3 = 153。
Armstrong numbers up to 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407
2. determine if a number is an Armstrong number
1. Let's start with a simple code to determine whether a number is an Armstrong number or not;
Let's take a look at the one 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; }
Run results:
Next look at Python
num = int(input("Please enter a number:")) sum= 0 n = len(str(num)) temp = num while temp >0: digit = temp %10 # Getting single digits sum += digit**n # Accumulate the results of the calculations temp //= 10 if num == sum : print("Fantastic!",num,"It's the Armstrong number.") else: print("It's a shame!",num,"Not the Armstrong number.")
Run results:
2. Write a search for a fixed range of Armstrong numbers
python implementation:
lower = int(input("Minimum:")) upper = int(input("Maximum:")) print("Here's what you want from{}until (a time){}The Armstrong number between\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 # Getting single digits sum+= digit**n # Accumulate the results of the calculations temp //= 10 if num == sum: print(num)
Run 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; }
The results of the run are shown:
C++ is too complicated, you can't learn from python, what a friendly language, learn C++ mind blowing the next day, if it helps you click a follow!
To this point this article on C++ and python to achieve the Armstrong number to find the article is introduced to this, more related to C++ and python Armstrong number to find the contents of the search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!