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

标签 c numbers

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/

相关文章:

Python检查输入中是否有数字?

一组数字中数字的重要性的php

python - 如何让 Python GUI 调用用 C 编写的遗传算法

c - strcpy 函数无法正常工作

c - 如何从命令行提供标准输入?

node.js - 为什么node.js v12.0.0以另一种方式处理32位以上的数字?

SQL Server : How to replace whitespaces(&nbsp, ASCII)在带数字的字符串中?

c - C 中的指针,导致段错误

c - 从客户端传递多条消息 ->服务器和服务器 -> C中的客户端套接字

lua - 如何使用 Lua 脚本在 Redis 中操作数字