友好数字函数给出了错误的结果
Amicable numbers function gives the wrong result
正如 this link 所描述的,我必须创建一个代码来计算范围内所有友好数字的总和。我拥有的代码:
#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
正如 this link 所描述的,我必须创建一个代码来计算范围内所有友好数字的总和。我拥有的代码:
#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