下面是一個C語言函數isPerfect的實現,該函數檢查一個整數x是否是完美數:
#include <stdio.h>
int isPerfect(int x) {
int sum = 0;
// 找出所有小於x的因數並計算它們的和
for (int i = 1; i <= x / 2; i++) {
if (x % i == 0) {
sum += i;
}
}
// 如果因數和等於x,則x是完美數
if (sum == x && x != 0)
return 1;
else
return 0;
}
int main() {
int number = 6;
if (isPerfect(number))
printf("%d is a perfect number.\n", number);
else
printf("%d is not a perfect number.\n", number);
return 0;
}
在這個函數中,我們通過一個迴圈找出x的所有因數(除了x本身),然後計算這些因數的和。如果這個和等於x,並且x不為0(因為0不是完美數),則函數返回1,表示x是一個完美數。否則,返回0,表示x不是一個完美數。