In: Computer Science
In this question, you should complete the C program, perfect.c, by implementing the function isPerfect. Open the file perfect.c, complete, compile and run it. When you are sure it is correct, include the c file in your final submission.
* Note: You should first carefuly read the COMMENTS provided for the function isPerfect, and then start completing the function.
* Note: You MUST NOT alter the main function and the prototype/header of the isPerfect function. ONLY develop the body of the function isPerfect.
A perfect number:
An integer number is said to be a perfect number if its factors,
including 1 (but not the
number itself), sum to the number.
Examples:
6 is a perfect number because its factors, except itself, are 3, 2,
and 1, and 6 = 3+2+1.
12 is not a perfect number because its factors, except itself, are 6, 4, 3, 2, and 1, but 12 ≠ 6+4+3+2+1.
The code:
#include <stdio.h>
/*
* An integer number is said to be a perfect number if its factors,
including 1 (but not the number itself), sum to the number.
* For example, 6 is a perfect number because its factors, except
itself, are 3, 2, and 1, and 6 = 3+2+1, but 12 is not a
perfect
* number because its factors, except itself, are 6, 4, 3, 2, and 1,
but 12 ≠ 6+4+3+2+1.
* This function determines whether its integer parameter, num, is a
perfect number or not by returning 1 if the number is a perfect
number,
* and 0 otherwise.
*/
int isPerfect(int num);
int main(void) {
for (int i=1; i<=1000;i++) {
if (isPerfect(i))
printf("%d is
perfect.\n", i);
}
}
int isPerfect(int num) {
// Complete the code of the function
}
Screenshot of program code:-
Screenshot of output:-
Program code to copy:-
#include <stdio.h>
/*
* An integer number is said to be a perfect number if its factors,
including 1 (but not the number itself), sum to the number.
* For example, 6 is a perfect number because its factors, except
itself, are 3, 2, and 1, and 6 = 3+2+1, but 12 is not a
perfect
* number because its factors, except itself, are 6, 4, 3, 2, and 1,
but 12 ? 6+4+3+2+1.
* This function determines whether its integer parameter, num, is a
perfect number or not by returning 1 if the number is a perfect
number,
* and 0 otherwise.
*/
int isPerfect(int num);
int main(void) {
for (int i=1; i<=1000;i++) {
if (isPerfect(i))
printf("%d is perfect.\n", i);
}
}
int isPerfect(int num) {
int sum = 0;
for(int i=1; i<num; i++) {
if(num%i == 0)
sum += i;
}
if(sum == num)
return 1;
else
return 0;
}