Munchausen numbers | Rosetta Code | #10
URL to the problem page: http://rosettacode.org/wiki/Munchausen_numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Find all Munchausen numbers between 1 and 5000.
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Find all Munchausen numbers between 1 and 5000.
#include <iostream>
using namespace std;
int power(int a, int b) {
int result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
int main() {
int tmp, digits, sum;
cout << "Munchausen numbers between 1 and 5000 are:" << endl;
for (int i = 1; i <= 5000; i++) {
tmp = i;
digits = 1;
sum = 0;
while (tmp >= 10) {
digits++;
tmp /= 10;
}
int* numbers = new int[digits];
for (int j = 0; j < digits; j++) {
numbers[j] = (i % power(10, j + 1)) / power(10, j);
sum += power(numbers[j], numbers[j]);
}
if (sum == i) {
cout << i << endl;
}
}
return 0;
}
Comments
Post a Comment