Dremendo Tag Line

Input two numbers and check if they form an amicable pair or not using a function in C

Function - Question 7

In this question, we will see how to input two numbers and check if they form an amicable pair or not in C programming using a function. To know more about function click on the function lesson.

Q7) Write a program in C to input two numbers and check if they form an amicable pair or not using a function. The function should return 1 if the numbers form an amicable pair else return 0.

An amicable pair is such that, the sum of the factors excluding itself of first number is equal to the second number and sum of factors excluding itself of the second number is equal to the first number. Example, (220, 284) are amicable pair since sum of factors excluding itself of first number is 284 and sum of factors excluding itself of second number is 220:

220=1+2+4+5+10+11+20+22+44+55+110=284
284=1+2+4+71+142=220

Program

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

int amicable(int a,int b)
{
    int fs1=0;   // factor sum of first number
    int fs2=0;   // factor sum of second number
    int i;

    for(i=1; i<a; i++)
    {
        if(a%i==0)
        {
            fs1=fs1+i;
        }
    }

    for(i=1; i<b; i++)
    {
        if(b%i==0)
        {
            fs2=fs2+i;
        }
    }
    if(fs1==b && fs2==a)
    {
        return 1;
    }
    return 0;
}

int main()
{
    int a,b;
    printf("Enter 2 numbers\n");
    scanf("%d",&a);
    scanf("%d",&b);
    if(amicable(a,b)==1)
    {
        printf("Amicable Pair");
    }
    else
    {
        printf("Not Amicable Pair");
    }
    return 0;
}

Output

Enter 2 numbers
220
284
Amicable Pair
video-poster