如this链接所述,我必须创建一个代码来计算范围内所有友好数字的和。我有以下代码:
#include <stdio.h>
int SumProperDivisors(int Number);
int main(void) {
//a != b , if d(b) = a ve d(a) = b
int DividedSum = 0;
int index = 0;
int temp = 0;
int sum = 0;
for(index = 1; index<10000; index++)
{
DividedSum = SumProperDivisors(index); //a
temp=SumProperDivisors(DividedSum); //b
if(DividedSum!=temp)
{
if(SumProperDivisors(temp)==DividedSum&&SumProperDivisors(DividedSum)==temp)
{
// printf("%d ",index);
sum +=index;
printf("%d ",sum);
}
}
}
printf("\n\n%d",sum);
return 0;
}
int SumProperDivisors(int Number)
{
int index;
int sum = 0;
for(index = 1; index < Number; ++index)
{
if((Number%index)==0)
{
sum += index;
}
}
return sum;
}
产生错误的
63968
结果,而正确的结果应为31626
。我是问一个朋友的名字。那我在做什么错?
最佳答案
找到(220,284)后,您需要记录已找到284,否则,当循环迭代到284时,它将再次找到220。
在VB中,粗心大意,不考虑优化。
Sub ListAmicablePairs()
Dim alreadyFound As New List(Of Integer)
For i = 1 To 9999
Dim spd1 = SumProperDivisors(i)
Dim spd2 = SumProperDivisors(spd1)
If spd2 = i AndAlso spd1 <> i AndAlso Not alreadyFound.Contains(i) Then
alreadyFound.Add(i)
alreadyFound.Add(spd1)
Console.WriteLine("({0}, {1})", i, spd1)
End If
Next
Console.WriteLine(alreadyFound.Sum())
End Sub
输出:
(220,284)
(1184,1210)
(2620、2924)
(5020,5564)
(6232,6368)
31626
关于c - 亲和数字功能给出错误的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28330806/