- The Modern C++ Challenge
- Marius Bancila
- 341字
- 2021-06-25 22:01:24
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).
- Apache ZooKeeper Essentials
- Android項(xiàng)目開發(fā)入門教程
- Visual FoxPro程序設(shè)計(jì)教程
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- C#程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 青少年信息學(xué)競(jìng)賽
- Learning Unreal Engine Android Game Development
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)教程(Windows 7+Office 2010)
- BeagleBone Robotic Projects(Second Edition)
- Python大規(guī)模機(jī)器學(xué)習(xí)
- LabVIEW入門與實(shí)戰(zhàn)開發(fā)100例(第4版)
- Learning Alfresco Web Scripts
- Access 2016數(shù)據(jù)庫應(yīng)用與開發(fā):實(shí)戰(zhàn)從入門到精通(視頻教學(xué)版)
- 秒懂算法:用常識(shí)解讀數(shù)據(jù)結(jié)構(gòu)與算法
- PHP高性能開發(fā):基礎(chǔ)、框架與項(xiàng)目實(shí)戰(zhàn)