Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
// armstrong number is a number = sum of cubes of its digit 
// ex: 153 = 1^3 + 5^3 + 3^3 --> 153 is an armstrong number
//write a program to input two natural m and n, then find an display to screen all Armstrong numbers from m to n.

#include<iostream>
#include<math.h>
using namespace std;
int main() {
	int m, n;
	cout << "Enter a natural m: ";
	cin >> m;
	cout << "Enter a natural n: ";
	cin >> n;
	
	cout << "Armstrong numbers from " << m << " to " << n << " are: " << endl;
	
	int i = m;
	while(i <= n) {
		int num = i;
		int temp = num;
		int sum = 0;
		int cnt = 0;
		while(num > 0) { // dem so luong chu so trong num
			++cnt;
			num /= 10;
		}
		num = temp;
		while(num != 0) {
			sum += pow(num%10, cnt);
			num /= 10;
		}
		if(sum == i) {
			cout << i << " ";
		}
		++i;	
	}
	return 0;
}


What I have tried:

i just want to discuss this exercise only in main function, using while (or do-while) loop (because my teacher asked me to do so .-.)
i have to watch a lot on youtube and also ask chatgpt, but it not work very well (not match the teacher's requirements)
Posted
Updated 6-Nov-23 21:40pm
Comments
Richard MacCutchan 7-Nov-23 3:45am    
You need to explain exactly what is wrong with your code.

1 solution

Your program looks correct to me.
A run with m=0, n=10000, produced a sequence matching the one you may find in this page: Narcissistic number - Wikipedia[^].
 
Share this answer
 
Comments
Như Quỳnh 2023 7-Nov-23 4:59am    
ok thanks
i got it
CPallini 7-Nov-23 5:15am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900