题目:在3位的正整数中,比如abc,有一些可以满足a3 + b3 + c3 = abc的条件,也就是说,各个位数的立方和正好是该数的本身,这些数就叫做Armstrong数。试写一个程序求出所有的3位Armstrong数
#include <iostream> using namespace std; void printArmstrong() { int leftValue; int midValue; int rightValue; for (int i = 100; i <= 999; i++) { leftValue = i / 100; midValue = (i / 10) % 10; rightValue = i % 10; if (leftValue * leftValue * leftValue + midValue * midValue * midValue + rightValue * rightValue * rightValue == i) { cout << "armstrong: " << i << endl; } } } void main() { printArmstrong(); }
#include <iostream> using namespace std; void printArmstrong() { for (int i = 1, i100 = 100; i <= 9; i++, i100 += 100) { int leftCube = i * i * i; for (int j = 0, j10 = 0; j <= 9; j++, j10 += 10) { int midCube = j * j * j; for (int k = 0, k0 = 0; k <= 9; k++, k0++) { int rightCube = k * k * k; if ((i100 + j10 + k0) == (leftCube + midCube + rightCube)) cout << "armstrong: " << leftCube + midCube + rightCube << endl; } } } } void main() { printArmstrong(); }
利用公式(p + 1)^3 = p^3 + 3p^2 + 3p + 1 和 (p + 1)^2 = p^2 + 2p + 1对上述代码进行优化:
#include <iostream> #include <iterator> #include <algorithm> using namespace std; int squareArray[10]; int cubeArray[10]; void printArmstrong() { *squareArray = 0; *cubeArray = 0; for (int i = 1; i < 10; i++) { squareArray[i] = squareArray[i - 1] + 2 * (i - 1) + 1; } for (int i = 1; i < 10; i++) { cubeArray[i] = cubeArray[i - 1] + 3 * squareArray[i - 1] + 3 * (i - 1) + 1; } for (int i = 1, i100 = 100; i <= 9; i++, i100 += 100) { int leftCube = cubeArray[i]; for (int j = 0, j10 = 0; j <= 9; j++, j10 += 10) { int midCube = cubeArray[j]; for (int k = 0, k0 = 0; k <= 9; k++, k0++) { int rightCube = cubeArray[k]; if ((i100 + j10 + k0) == (leftCube + midCube + rightCube)) cout << "armstrong: " << leftCube + midCube + rightCube << endl; } } } } void main() { printArmstrong(); }