Start New Discussion within our Software Development Community

Hey I have this program that I'm having some trouble figuring out so maybe someone can give me some helpfuls hints. Here goes:

I have to find all numbers between 1 to 999 who when their digits are cubed individually and then all added together, equal the original number. For example take the number 371. Cube the 3 + cube the 7 + cube the 1 = 371. I know how to do most of the problem but I'm not sure how to get each digit alone. I'm sure there is some command to do this in C++ that I simply haven't learned yet. I also figured out that to get the three alone I could just divide it by 100 and label it as an int so the ".71" would just be scratched out. But I'm not sure how I would do this for the 7 and the 1. Any help or hints would be appreciated. Thanks.

#include <iostream>
#include <cstdlib>
#include <cctype>
int main()
{
   const char text[] = "371", *digit;
   int value, sum, cube;
   // Use the text from most significant digit to least significant digit
   for ( digit = text, sum = 0; *digit; ++digit )
   {
	  value = *digit - '0';
	  cube = value * value * value;
	  sum += cube;
	  std::cout << value << " cubed = " << cube << std::endl;
   }
   std::cout << "sum = " << sum << std::endl;
   // Use an integer from least significant digit to most significant digit
   for ( value = std::atoi(text), sum = 0; value; value /= 10 )
   {
	  int temp = value % 10;
	  cube = temp * temp * temp;
	  sum += cube;
	  std::cout << temp << " cubed = " << cube << std::endl;
   }
   std::cout << "sum = " << sum << std::endl;
   return 0;
}
/* my output
3 cubed = 27
7 cubed = 343
1 cubed = 1
sum = 371
1 cubed = 1
7 cubed = 343
3 cubed = 27
sum = 371
*/
This article has been dead for over six months. Start a new discussion instead.