In this example you are allowed to use from the C standard library only functions for input and output (e.g. printf(), scanf())
Complete the following functions using C programming language:
A positive integer number is said to be a perfect number if its positive factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number because 6=1+2+3. Complete the int Q6(intQ6_input, int perfect[])function that determines all perfect numbers smaller than or equal to some integer Q6_input(Q6_input> 1).
Note: Assume that x and y are two positive integers. Then x is a factor of y if the remainder of the division of y by x is 0. For instance, 5 is a factor of 15, but not of 36.
For example: if Q6_inputis 10 then the only perfect number you will find is 6. Accordingly, perfect[0] should be equal 6 and the function should return 1 as your count.
Code:
#include<stdio.h>
int Q6(int Q6_input, int *perfect)
{
int i,j,count=0,factSum;/*Declaring variables*/
for(i=6;i<=Q6_input;i++)
{/*This loop iterates for 6 to Q6_input
because 6 is the first perfect number*/
factSum=0;/*For every iteration we
make factors sum to 0*/
for(j=1;j<i;j++)
{
/*This loop
iterates for 1 to i-1 values*/
if(i%j==0)
{/*If i is
divisible by j then we add it to the factsum*/
factSum+=j;
}
}
if(factSum==i)
{/*If factsum is equals to the
i
then we append
it to the perfect array*/
*(perfect+count)=i;
count++;
/*Here we
increase the count*/
}
}
return count;/*Here we return the count of the perfect
numbers*/
}
int main()
{
int num,i,perfect[100],count;/*Declaring
variables*/
printf("Enter a number to print perfect numbers below
a given number:");
scanf("%d",&num);/*Here we read the input from the
user*/
count=Q6(num,perfect);/*Here we call the function by
passing the num and array reference*/
if(count==0)
{/*If count is 0 means no perfect numbers in the
range*/
printf("There are no perfect
numbers in the given range");
}
else
{/*IF count is greater than 0 we print the perfect
numbers*/
printf("Perfect numbers in the
given range are:\n");
for(i=0;i<count;i++)
{
printf("%d\n",perfect[i]);
}
}
}
Output:
Indentation:
Get Answers For Free
Most questions answered within 1 hours.