Wednesday, 3 September 2014

C Program to check Amicable Numbers

Amicable numbers are two different numbers so related that the sum of the proper divisors of first number is equal to the other number and vice-versa. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.).

For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.

The first few amicable pairs are: (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368).

Following is a C language program to check the given two numbers are amicable or not.


#include <stdio.h>
#include <conio.h>

int  main() {
    int i, sf1=0, sf2=0,  m, n;

    clrscr();
    printf("Enter the first number :");
    scanf("%d", &m);
    printf("Enter the second number :");
    scanf("%d",&n);

    if (m==n) {
       printf("Given numbers are not amicable");
       getch();
       return 0;
    }

   / * Finds sum of proper divisors of the first number (m) */
    for (i=1;i<=m/2;i++){
        if (m%i==0)
            sf1=sf1+i;
        }

 / * Finds sum of proper divisors of the second number (n) only if sum of proper divisors of first number is equal to the second number */

    if (sf1==n)
        for (i=1; i<=n/2;i++){
            if (n%i==0)
                sf2=sf2+i;
        }

     if (sf2==m)
        printf ("Given numbers are amicable");
     else
        printf("Given numbers are not amicable");

     
     getch();
     return 0;
}

No comments:

Post a Comment