I am trying to print out the first few numbers that follow a certain rule: the sum of its digits can be raised to an integral power to get the number itself. (Basically if the sum is an nth root of the number).
For example, the sum of the digits in the number 81 is 9, and 9^2 is 81.
This is some of the code I am using:
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int sumOfDigits(int num) {
int sum = 0;
string numStr = "";
stringstream s;
s << num;
s >> numStr;
for (int i = 0; i < numStr.length(); i++) {
int ad = 0;
stringstream ss;
ss << numStr[i]; // take each digit
ss >> ad;
sum += ad; // and add to sum
}
return sum;
}
int num = 10; // starting number
int numFound = 0; // how many such special numbers have been found
int main() {
while (numFound < 5) {
int sum = sumOfDigits(num);
double exp = log10(num) / log10(sum);
if (fmod(exp, 1.0) == 0.0 && sum != 1) { // if the exponent is an integer
cout << num << "\t" << sum << endl; // then print out the number and the sum of its digits
numFound++;
}
num++;
}
return 0;
}
When I run this, I get the following output:
81 9
2401 7
4913 17
5832 18
17576 26
The second entry should be 512
and 8
because 8^3 is 512. I don't understand why the test works with some numbers but doesn't work with others.
I've tried other methods of testing whether the exponent is an integer as well. I've tested it against the floor()
expression, and I've tried casting the entire expression with (int)
.
I may be wrong and the problem may not be in that spot, but I would really appreciate it if you could help me with this. Thank you.