这是我为CodeForces问题919B找到的一个解决方案--完美数。从技术上讲,我理解它在做什么,但我想理解它背后的‘直觉’或想法/方法。
int main(){
int k=0, m=19, c=0, sum=0;
scanf("%d", &k);
while(true){
int n = m;
sum = 0;
while(n){
sum+=n%10;
n=n/10;
}
printf("%d %d %d\n", n, sum, c);
if(sum == 10) c++;
if(c == k) break;
m++;
}
printf("%d", m);
return 0;
}发布于 2018-02-02 03:44:50
用户0x499602D2已经给出了一个非常简洁的答案,但让我详细说明一下。超高级伪代码将如下所示:
loop over natural numbers and check if they are perfect:
if found k such numbers:
stop and output the last perfect number下面是一个更详细的伪代码,它与您的c++代码片段相匹配:
m = 19 # first perfect number (1+9=10) - a good starting point
c = 0 # total number of perfect numbers found so far
sum = 0 # temporary variable that will hold the sum of digits
read k from stdin # we're going to look for the k-th perfect number
# we start an open-ended search but we know that we will find k-th number and stop
for m = 19 ... infinity:
if m is perfect:
increment c by one # found c perfect numbers so far
if c == k:
exit loop and return m # m is the k-th perfect number! we're done!看看c与我们找到的“完美数”的数量是如何对应的?一旦c命中k,我们的循环就可以停止。
还有一个技术问题:我们如何检查数字1945是否完全正确?我们需要对数字求和: 1+9+4+5。从数字n中获得最低有效数字的简单方法是将除数的余数除以10 (即n modulo 10):
1945 % 10 = 5
194 % 10 = 4
19 % 10 = 9
1 % 10 = 1如何从1945到194再到19到1?只需做整数除以10:
1945/10 = 194
194/10 = 19
19/10 = 1
1/10 = 0 -> stop the loop, since while(0) is the same as while(false)这就是在printf之前发生的事情。
https://stackoverflow.com/questions/48569907
复制相似问题