C++ Program to check whether two numbers are Friendly Pair(Amicable number) or not

Program to check whether two numbers are Friendly Pair(Amicable number) or not

Amicable numbers are two different numbers related in a way such that the sum of the proper divisors of each is equal to the other number. A proper divisor is a positive factor of that number other than the number itself ,for Example proper divisors of 6 are 1, 2, and 3.

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

Program to check for Amicable numbers

Algorithm:-

  1. User gives two inputs(numbers to check).
  2. Inputs are stored in int type variables say first & second.
  3. A function findAmicable() is called with first and second as parameters.
    1. Divisors of first are found, added and stored in an int type variable say sum1.
    2. Divisors of second are found, added and stored in another variable sum2.
    3. If first is equal to sum2 and second is equal to sum1 then they are Amicable numbers
    4. Otherwise they are not Amicable numbers

C++ Code:-

    
    //C++ Program
    //Friendly Pair(Amicable number) or not
    #include<iostream>
    using namespace std;
    // function to check Friendly pairs
    void findAmicable(int firstint second)
    {
        int sum1=0,sum2=0;
        for(int i=1i<=first/2 ; i++)
        {
            //finding and adding divisors of first number
            if(first%i==0)
                sum1=sum1+i;
        }
        for(int i=1i<=second/2 ; i++)
        {
            //finding and adding divisors of second number
            if(second%i==0)
                sum2=sum2+i;
        }
        //ckecking for friendly pair
        if(first==sum2 && second==sum1)
            cout<<“Fiendly Pair(“<<first<<“,”<<second<<“)”;
        else
            cout<<“Not a Fiendly Pair”;
    }
    //main program
    int main()
    {
        int first,second;
        cout<<“Enter first number : “;
        //user input
        cin>>first;
        cout<<“Enter second number : “;
        //user input
        cin>>second;
        //calling function
        findAmicable(first,second);
        return 0;
    }

    Output

    Enter first number : 220
    Enter second number : 284
    Fiendly Pair(220,284)