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;
}

2 comments:

Anonymous said...

there is a bug in the code. For 100000 repeats pairs

codescott said...

I have an amicable number search program that uses a theorem by Leonard Euler to determine the sum of the proper divisors of a number. While I don't have any timings, I suspect that this program is faster than just dividing by all the numbers less than the square root.