官术网_书友最值得收藏!

8. Armstrong numbers

An Armstrong number (named so after Michael F. Armstrong), also called a narcissistic number, a pluperfect digital invariant, or a plus perfect number, is a number that is equal to the sum of its own digits when they are raised to the power of the number of digits. As an example, the smallest Armstrong number is 153, which is equal to .

To determine if a number with three digits is a narcissistic number, you must first determine its digits in order to sum their powers. However, this involves pision and modulo operations, which are expensive. A much faster way to compute it is to rely on the fact that a number is a sum of digits multiplied by 10 at the power of their zero-based position. In other words, for numbers up to 1,000, we have a*10^2 + b*10^2 + c. Since you are only supposed to determine numbers with three digits, that means a would start from 1. This would be faster than other approaches because multiplications are faster to compute than pisions and modulo operations. An implementation of such a function would look like this:

void print_narcissistics()
{
for (int a = 1; a <= 9; a++)
{
for (int b = 0; b <= 9; b++)
{
for (int c = 0; c <= 9; c++)
{
auto abc = a * 100 + b * 10 + c;
auto arm = a * a * a + b * b * b + c * c * c;
if (abc == arm)
{
std::cout << arm << std::endl;
}
}
}
}
}

You could take it as a further exercise to write a function that determines the narcissistic numbers up to a limit, regardless their number of digits. Such a function would be slower because you first have to determine the sequence of digits of the number, store them in a container, and then sum together the digits raised to the appropriate power (the number of the digits).

主站蜘蛛池模板: 博野县| 特克斯县| 吉安市| 观塘区| 安阳县| 蒙山县| 华池县| 互助| 正定县| 遵义市| 孝义市| 铅山县| 康保县| 黔江区| 沾益县| 贵港市| 共和县| 乃东县| 保德县| 金门县| 清新县| 于都县| 鱼台县| 昔阳县| 湟中县| 奉化市| 黔江区| 西昌市| 蚌埠市| 平泉县| 泽普县| 定西市| 漳平市| 淮滨县| 克拉玛依市| 新竹县| 临朐县| 临颍县| 龙山县| 南城县| 涞水县|