由于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
。我是以朋友的名义问这个。
那么我做错了什么?
答案 0 :(得分:1)
当你找到(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