C-查找限制之间的所有友好数字 [英] C - Find all amicable numbers between limits

查看:89
本文介绍了C-查找限制之间的所有友好数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个定义:友好的数字对由两个不同的整数组成,其中 第一个整数的除数之和等于第二个整数,并且 第二个整数的除数之和等于第一个整数.完美数字是等于其自身除数之和的数字.

First a definition: An amicable pair of numbers consists of two different integers where the sum of the divisors of the first integer is equal to the second integer, and the sum of the divisors of the second integer is equal to the first integer. A perfect number is a number that equals the sum of its own divisors.

我想做的是制作一个程序,要求用户提供一个下限和一个上限,然后向他/她提供这两个限制之间的所有友好对(每行一对).如果有一个完美的数字,则只需要打印一个数字(在这种情况下,则不需要成对打印).

What I want to do is make a program that asks the user for a lower limit, and an upper limit and then presents him/her with all the amicable pairs (one per line) between those two limits. If there's a perfect number only one number needs to be printed (not a pair in its case).

整个想法让我很困惑,所以我正在寻找帮助.

The whole idea is pretty confusing to me, so I'm looking for some assistance.

这是我必须开始的内容,我知道sumDivisors()或多或少应该正确,但是main()只是在检查两个输入的数字是否友好-可能必须对此进行彻底的检查因为我希望所有对都在两个给定的限制之间.

Here's what I have to start with, I know that sumDivisors() should be more or less correct, but main() is merely checking if the two inputted numbers are amicable or not - might have to do a complete overhaul of this since I want all the pairs between two given limits.

long sumDivisors(long a)
{
    long s=0,i;
    for(i=1;i<=a/2;i++)
    {
        if(a%i==0)
        {
            s+=i;
        }
    }
    return s;
}


int main()
{
    long t,n,s1;
    scanf("%ld",&t);
    while(t--)
    {
        scanf("%ld",&n);
        s1=sumDivisors(n);
        if(n==sumDivisors(s1))
        {
            printf("Yes\n");
        }
        else printf("No\n");
    }
    return 0;
} 

推荐答案

您可以这样编写main():

You could write main() like this:

int main ()
{
    // assumes 1 <= min <= max                                                                
    long min = 1;
    long max = 10000;

    for (long a = min; a <= max; a++) {
        long b = sum_of_proper_divisors (a);
        if (a == b) {
            printf ("perfect number:\t%ld\n", a);
        }
        if ((a < b) && (b <= max) && (sum_of_proper_divisors (b) == a)) {
            printf ("amicable pair:\t(%ld, %ld)\n", a, b);
        }
    }

    return 0;
}

这篇关于C-查找限制之间的所有友好数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆