Dremendo Tag Line

Input 2 integers and check amicable pair or not using while loop in C++

while Loop - Question 9

In this question, we will see how to input two integers and check if it forms an amicable pair or not in C++ programming using while loop. To know more about while loop click on the while loop lesson.

Q9) Write a program in C++ to input two integers and check if it forms an amicable pair or not using while loop.

An amicable pair is such that, the sum of the factors excluding itself of first number is equal to the second number and the sum of factors excluding itself of the second number is equal to the first number.

Example, (220, 284) is an amicable pair since, sum of factors excluding itself of: 220 = 1+2+4+5+10+11+20+22+44+55+110 = 284 and sum of factors excluding itself of: 284 = 1+2+4+71+142 = 220

Program

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int i=1,n1,n2,sf1=0,sf2=0;

    cout<<"Enter 2 numbers\n";
    cin>>n1>>n2;

    while(i<n1)
    {
        if(n1%i==0)
        {
            sf1=sf1+i; 		// sum of factors of 1st number
        }
        i=i+1;
    }

    i=1;
    while(i<n2)
    {
        if(n2%i==0)
        {
            sf2=sf2+i; 		// sum of factors of 2nd number
        }
        i=i+1;
    }

    if(sf1==n2 && sf2==n1)
    {
        cout<<"Amicable Pair";
    }
    else
    {
        cout<<"Not Amicable Pair";
    }
    return 0;
}

Output

Enter 2 numbers
220
284
Amicable Pair
video-poster