Skip to content

Armstrong number

Intro

An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.

For example:

  • 9 is an Armstrong number, because 9 = 9^1 = 9
  • 10 is not an Armstrong number, because 10 != 1^2 + 0^2 = 1
  • 153 is an Armstrong number, because: 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
  • 154 is not an Armstrong number, because: 154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190

Task

Write some code to determine whether a number is an Armstrong number.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include "armstrong_numbers.h"
#include <cmath>
#include <cstdint>
#include <string>

namespace armstrong_numbers {
bool is_armstrong_number(std::uint32_t test)
{
    if(test<10)return true;
    std::string tmp=std::to_string(test);

    std::uint32_t tmp2{};
    for(auto &n:tmp)
    {
        int base=n-'0';
        tmp2+=pow(base,tmp.size());
    }
    return tmp2==test?true:false;
}
}  // namespace armstrong_numbers
1
2
3
4
5
6
7
8
9
#include <cstdint>
#if !defined(ARMSTRONG_NUMBERS_H)
#define ARMSTRONG_NUMBERS_H

namespace armstrong_numbers {
bool is_armstrong_number(std::uint32_t);
}  // namespace armstrong_numbers

#endif // ARMSTRONG_NUMBERS_H

Last update: February 13, 2021

Comments