6-3 使用函式輸出指定範圍內的完數 (20分)

始不垂翅發表於2020-11-09

6-3 使用函式輸出指定範圍內的完數 (20分)

懶得複製了
在這裡插入圖片描述

正確答案:(別光顧著複製啊,記得摘出來?)

#include<stdio.h> 
#include<stdlib.h>
#include<math.h>
int factorsum( int number );
void PrintPN( int m, int n );
int main()
{
    int m, n;

    scanf("%d %d", &m, &n);
    if ( factorsum(m) == m ) printf("%d is a perfect number\n", m);
    if ( factorsum(n) == n ) printf("%d is a perfect number\n", n);
    PrintPN(m, n);

    system("pause");
}
int factorsum( int number )//求這個數的因子和
{
    int i = 1,sum = 0;
    while (i<=number/2)
    {
        if(number%i==0)
        {
            sum+=i;
        }
        i++;
    }
    return sum;
}
void PrintPN( int m, int n )
{
    int num = m,a = 0,i=2;//a表示完數個數
    while (num <= n)
    {
        if (factorsum(num) == num)//是不是完數
        {
            printf("%d = %d",num,1);
            while (i<=num/2)
            {
                if (num%i==0)
                {
                    printf(" + ");
                    printf("%d",i);
                }
                i++;
            }
            printf("\n");
            a++;
            i = 2;
        }
        num++;
    }
    if (a == 0)
    {
        printf("No perfect number");
    }
    
}

相關文章