How to print all armstrong numbers from 1 to N in C++

1 Answer

0 votes
// Armstrong = a number that equals the sum of its digits, 
//             each raised to a power of the number of digits
// For example 153, it's an Armstrong number because 1^3 + 5^3 + 3^3 = 153

#include <iostream>
#include <cmath>
 
bool armstrong(int n) {
    int reminder = 0, sum = 0, total_digits = log10(n) + 1;
    int temp = n;
    
    while (temp > 0) {
        reminder = temp % 10;
        sum += pow(reminder, total_digits);
        temp = temp / 10;
    }
        
    if (sum == n) {
        return true;
    }
         
    return false;
}

int main(void) {
    int N = 500; 

    for (int i = 1; i <= N; i++) {
        if (armstrong(i)) {
            std::cout << i << ", ";
        }
    }
}
    
    
    
    
/*
run:
    
1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 
    
*/

 



answered Dec 26, 2023 by avibootz

Related questions

1 answer 150 views
1 answer 136 views
1 answer 195 views
1 answer 150 views
1 answer 121 views
...