【发布时间】:2016-11-12 15:00:02
【问题描述】:
示例:
输入:|输出:
5 –> 12 (1^2 + 2^2 = 5)
500 -> 18888999 (1^2 + 8^2 + 8^2 + 8^2 + 9^2 + 9^2 + 9^2 = 500)
我已经编写了一个非常简单的蛮力解决方案,但它存在很大的性能问题:
#include <iostream>
using namespace std;
int main() {
int n;
bool found = true;
unsigned long int sum = 0;
cin >> n;
int i = 0;
while (found) {
++i;
if (n == 0) { //The code below doesn't work if n = 0, so we assign value to sum right away (in case n = 0)
sum = 0;
break;
}
int j = i;
while (j != 0) { //After each iteration, j's last digit gets stripped away (j /= 10), so we want to stop right when j becomes 0
sum += (j % 10) * (j % 10); //After each iteration, sum gets increased by *(last digit of j)^2*. (j % 10) gets the last digit of j
j /= 10;
}
if (sum == n) { //If we meet our problem's requirements, so that sum of j's each digit squared is equal to the given number n, loop breaks and we get our result
break;
}
sum = 0; //Otherwise, sum gets nullified and the loops starts over
}
cout << i;
return 0;
}
我正在寻找问题的快速解决方案。
【问题讨论】:
-
你的问题不是很好。例如,您可以说
any number -> 1111111...1111。这将是一个微不足道但正确但有效的解决方案。我认为你必须回到制定阶段。 -
问题说明“找到最小的整数,其数字的平方和与给定的数字相加”
-
我的错,你是对的!这个问题比看起来更有趣,可能应该更好地评估。我建议在问题正文中完整地陈述问题,而不是依赖问题标题。
-
我的基本原理是将
n除以81,得到9的数量。然后取还押,除以64,也就是8的个数,以此类推…… -
请注意,结果中数字的所有排列都具有相同的属性。因此,一种可能的解决方案可能是找到最小的完美平方集合
标签: c++ algorithm performance