gpt4 book ai didi

c - 友好数字函数给出了错误的结果

转载 作者:行者123 更新时间:2023-11-30 15:24:38 25 4
gpt4 key购买 nike

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。我以 friend 的名义问这个问题。那么我做错了什么?

最佳答案

当你找到(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com