CS 153 Program 3- Amicable Numbers 220 284 An amicable pair of numbers consists
ID: 3755507 • Letter: C
Question
CS 153 Program 3- Amicable Numbers 220 284 An amicable pair of numbers consists of two different integers where the sum of the proper divisors of the first integer is equal to the second integer, and the sum of the proper divisors of the second integer is equal to the first integer. For example, (220, 284) is an amicable pair because 284 is divisible by 1, 2, 4, 71, and 142 and the sum of those is 220 220 is divisible by 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 and the sum of those is 284 Write a program that asks the user for an upper limit. The program finds all pairs of amicable numbers where the first number of the pair is less than the limit. The second number of the pair may or may not be greater than the limit. To do this sensibly, write a function int sumDivisors( int num) that returns the sum of all the proper divisors of num. The main program looks at each integer N up to the limit. For each N compute the sum S of its proper divisors Then check if the sum of the proper divisors of S is the original number N If N and S are the same number, then N is perfect. Write out amicable pairs and perfect numbers one per line. Write out just one number if it is perfect Write out each amicable pair just once. If both numbers of a pair are within the limits, then the pair will be found twice. So when a pair is found check that S is greater than N. If so, write out the pair. If not, then the lower number of the pair S has already been found as part of a pair Write sumDivisors (as a loop that checks trial divisors starting at 2 and going up until trial*trial > N. If N%trial-0, then add trial and N/trial to the sum Initialize the sum to 1 (since 1 divides N) Compile and test your program. Use ANSI-C syntax. Do not mix tabs and spaces. Do not use break or continue. Debug thoroughly. Turn in a complete source file using Blackboard. Start the source file with a comment block that briefly says what the program does, who wrote it, and the dateExplanation / Answer
Code:
#include<stdio.h>
int sumDivisors(int num)
{
// Sum of divisors initialized as 1
int sumOfDivisors = 1;
for (int trail = 2; trail*trail <= num; trail++)
{
if (num % trail == 0)
{
if (trail == (num / trail))
sumOfDivisors += trail;
else
sumOfDivisors += (trail + num/trail);
}
}
return sumOfDivisors;
}
int main() {
int limit,N,S;
printf("Enter limit: ");
scanf("%d",&limit);
for(N=1;N<=limit;N++){
int S = sumDivisors(N);
if(N==S){
printf("%d ",N); //perfect number
}
int sumDivS = sumDivisors(S);
if(sumDivS == N && S>N){
printf("%d %d ",N,S);//amicable number
}
}
}
Sample output:
Enter limit: 100000
1
6
28
220 284
496
1184 1210
2620 2924
5020 5564
6232 6368
8128
10744 10856
12285 14595
17296 18416
63020 76084
66928 66992
67095 71145
69615 87633
79750 88730