Write a program that asks the user for input for two integer values: startval ,
ID: 3548750 • Letter: W
Question
Write a program that asks the user for input for two integer values: startval, and endval. The program will then find all Perfect Numbers that fall between startval and endval.
A perfect number is a number equal to the sum of all its proper divisors (divisors smaller than the number) including 1. The number 6 is the smallest perfect number; because it is the sum of its divisors 1, 2, and 3 (1+2+3 = 6). The next perfect number is 28 (28 = 1+2+4+7+14).
The search for the Perfect Number will require two loops (nested). The outer loop will step thru the range of numbers between startval and endval. The inner loop will step thru the values from 1 to (outerval/2) to determine the factors of the number.
Write and use a function called isAFactor that accepts two int args, and determines if the second number is a factor of the first. It should return a bool value.
When a number is found, print out a message:
Xxx is a Perfect Number.
If no Perfect Numbers can be found in the given range, print the message:
No Perfect Numbers found between xxxx and yyyy.
Explanation / Answer
#include<stdio.h>
int AFactor(int x, int y)
{
//returns not (x modulo y) i.e. returns 1 if y divides x else 0
return !(x%y);
}
int main()
{
int startval, endval,outerval,sum,i;
startval = 2;
endval = 1000;
for(outerval=startval;outerval<=endval;outerval++)
{
//sum holds the sum of all its proper divisors
sum = 0;
for(i=1;i<=outerval/2;i++)
{
if(AFactor(outerval,i))
{
//if i is a factor of outerval then add i to sum
sum+=i;
}
}
//now sum has the sum of all of outerval's proper divisors, now check if it equals outerval
if(sum == outerval)
{
printf("%d ",outerval);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.