Created
May 13, 2013 12:35
-
-
Save keelerm84/5568021 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Coding challenge : Armstrong Numbers | |
* | |
* Write a program using any language or technique that can accept two positive | |
* integers defining a range (such as 0 and 100 for the range 0 <= x <= 100) and | |
* will print all Armstrong Numbers in that range. | |
* | |
* An Armstrong Number is fully defined at | |
* http://en.wikipedia.org/wiki/Narcissistic_number | |
* | |
* In short it is any number where the value is the same as the sum of it's | |
* digits raised to the power of the number of it's digits. | |
* | |
* So 153 = 1^3 + 5^3 + 3^3 | |
* | |
* Given the range 0 to 10,000 you should have the following output: | |
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474 | |
* | |
* We are assuming base 10. | |
*/ | |
#include <iostream> | |
bool is_armstrong(int number, int * powers) { | |
int sum = 0, temp = number; | |
while ( temp != 0 ) { | |
sum += powers[temp % 10]; | |
temp /= 10; | |
} | |
return sum == number; | |
} | |
void bump_powers(int * powers) { | |
for(int i = 2; i < 10; ++i) { | |
powers[i] *= i; | |
} | |
} | |
int main (int argc, char * argv[]) { | |
int digits = 0; | |
int mod = 10; | |
int powers[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; | |
for(int i = 0; i <= 1000000; ++i) { | |
if ( is_armstrong(i, powers) ) | |
std::cout << i << " "; | |
if ( ++digits % mod == 0 ) { | |
digits = 0; | |
mod *= 10; | |
bump_powers(powers); | |
} | |
} | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment