An integer x is a perfect number if the sum of the factors of x (including 1 but
ID: 3641463 • Letter: A
Question
An integer x is a perfect number if the sum of the factors of x (including 1 but not including x itself) is equal to x. For example, 6 is a perfect number since 6 = 1+2+3. Write a function that determines whether an integer is perfect.
int isperfect(int x);
The function returns 1 if x is a perfect number and 0 if it is not.
Write a main program that finds all the perfect numbers between 2 and 1000. The program will determine whether a number is perfect by calling the function isperfect. Print each perfect number on a separate line along with its expansion as a sum of factors. The factors should appear in ascending order. For example, the first line produced by your program should be
6 = 1 + 2 + 3
Explanation / Answer
#include<stdio.h>
#include<conio.h>
int isperfect(int);
void main()
{
int i;
clrscr();
for(i=2;i<=1000;i++) // generates number between 2 and 1000.
{
if(isperfect(i)==1) // if i is a perfect number,it is printed.
printf("%d ",i);
}
getch();
}
int isperfect(int n)
{
int i,sumfac=0; // sumfac calculates the sum of factors of n.
for(i=1;i<n;i++) // i generates numbers from 1 to n-1.
{
if(n%i==0)
sumfac+=i; // if i is a factor of n then it is added to sumfac.
}
if(sumfac==n) // if sumfac=n then 1 is returned.Else 0 is returned.
return 1;
else
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.