AMICABLE PAIRS PROGRAM IN C

Two numbers are said to be amicable if sum of proper divisors of 1st is equal to the 2nd and vice versa. It is assumed that these two numbers shoud be distinct, e.g. 3 is equal to the sum of its proper divisors 1 and 2 but can not form an amicable pair.




#include <stdio.h>
int main()
{
  long int range, test, chk, div, sum, n1, n2;
  printf("Input range to check amicable numbers: ");
  scanf("%ld", &range);
  test = 0;
  while ( ++test < range )
  {
            sum = div = 0;
            while ( ++div <= test/2 )
            {
                        if ( test % div == 0 )
                        sum += div;
            }
            chk = sum;
            sum = div = 0;
            while ( ++div <= chk/2 )
            {
                        if ( chk % div == 0 )
                        sum += div;
            }
             if ( sum == test )
            {
                        if ( test == chk )
                                    continue;
                        n1 = test;
                        if ( n1 == n2)
                                    continue;
                        n2 = chk;
                        printf("%d\t%d\n", n1, n2);
            }
  }
  return 0;
}
Post a Comment