Suppose you check the number 101. The first time through the loop, line 17 extracts the millions digit, which is 0. Then line 20 subtracts 1 million. leaving -999899. Now you're completely off the rails. The problem is that you started with the wrong digit.
The same sort of problem occurs if you check a 7 digit number: the first "digit" will be greater than 10.
Also, at line 32, if you found no Armstrong numbers then the a[0] will be uninitialized, not zero. So you'd have to initialize it to zero.
Overall you've made this more complicated than it needs to be:
- Why store the results? Why not just print them as you see them?
- Why extract the digits from the left? It's much easier to extract them from the right?
- Why store the digits from the left? Since the Armstrong calculation doesn't depend on the order of the digits, you can store them in any order.
Here's a version that extracts the digits from the right and stores then in the order extracted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
// Extract the digits in num and return them in a vector
vector<int> getDigits(int num)
{
vector<int> result;
while (num) {
result.push_back(num % 10);
num /= 10;
}
return result;
}
// Given the digits of a number, compute the sum of the digits raised
// to the size of the number.
int armstrongCalc(const vector<int> &digits)
{
int result = 0;
for (int digit : digits) {
result += pow(digit, digits.size());
}
return result;
}
int
main()
{
int n, m;
while (cin >> n >> m) {
for (int i = n; i <= m; i++) {
vector<int> digits = getDigits(i);
if (armstrongCalc(digits) == i) {
cout << i << '\n';
}
}
}
}
|
This runs but it's kind of slow. It could be sped up dramatically by precomputing the powers of the digits.