I am trying to write a function which finds all pairs of amicable numbers from 2 to a given upper range.
I wrote a function that finds the sum of divisors of a given number.
I also wrote a function that uses the fact that if sum of devisors of num1 is S(num1), and num2=s(num1)-num1 has the same sum of devisors, then num1 and num2 are amicable numbers.
Here is my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
void amicableNumbers(int n);
int findSumOfDevisors(int num);
void main() {
int upperRange;
printf("enter the value for upper range: ");
scanf("%d", &upperRange);
printf("the amicable numbers between 2 and %d:\n", upperRange);
amicableNumbers(upperRange);
}
void amicableNumbers(int n) {
int sum, sum2, i;
for (i = 2; i <= n; i++) {
sum = findSumOfDevisors(i);
if (sum > i && sum <= n) {
sum2 = findSumOfDevisors(sum);
if (sum2 == i)
printf("%d and %d \n", i, sum);
}
}
}
int findSumOfDevisors(int num) {
int sum = 1, i, n;
n = (int)sqrt((double)num);
for (i = 2; i <= n; i++) {
if ((n % i) == 0) {
sum += i;
sum += n / i;
}
}
return sum;
}
However, when I run this I get the wrong output. For instance, for the upperRange 301, I get that there are not any amicable numbers in the range 2-301.
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. For instance, the pair 220 and 284 are amicable numbers. The sum of the proper divisors of 220 is 1+2+4+5+10+11+20+22+44+55+110=284 and the sum of the proper divisors of 284 is 1+2+4+71+142=220.
A proper divisor to a number is a positive factor to that number except the number itself.
n =(int) sqrt((double)num);may not provide the integer square root desired given slight inaccurateracies possible withsqrt(). Suggest only using integer math:for (i = 2; i <= num/i; i++)- chux - Reinstate MonicafindSumOfDivisors* - Lee Taylormain()is alwaysint- user3629249scanf()family of functions, always check the returned value (not the parameter values) to assure the operation was successful. - user3629249