Program to find friend numbers between 2 to n

Two positive integers are said to be friends if each of their divisors' sum (excluding the number itself) equal to the other number.

Example:
the sum of all positive divisors of 220 i.e 1+2+4+5+10+11+20+22+44+55+110 is 284 and
sum of all divisors of 284 i.e 1+2+4+72+142 is 220.

Write a cpp program to find all friend numbers between 2 to n

Program:

/*                       cpp program to find friend numbers from 2 to N                         */

#include"iostream"

using namespace std;

int main()
{

    int num, sum = 0,sum2 = 0, i, j, k, count=0;
    do
    {
        cout<<"Enter a limit: ";       //get a number upto which to find friend number
        cin>>num;
   
        if(num<1)
        {
            cout<<"Enter a valid positive integer."<<endl;
      
        }
    }while(num<1);

    for(i=2; i<=num; i++)
    {
        sum = 0,sum2 = 0;                        //initializing to 0 for second iteration
        for(j=1; j<i; j++)
        {
            if(i%j == 0)
            {
                sum = sum + j;           //sum of the divisors of i
            }
        }

        for(k=1; k<=(sum/2); k++)
        {
            if(sum%k == 0)
            {
                sum2 = sum2 + k;         //sum of divisors of num
            }
        }
      
        if(i==sum2 && i!=sum && i<sum)
        {
            cout<<i<<" and "<<sum<<endl;
            count++;                          //counting total number of friend numbers
        }
      
    }
    if(count == 0)
    {
        cout<<"No friend numbers found below "<<num<<endl;
    }
    else
    {
        cout<<"Total "<<count<<" friend numbers found."<<endl;
    }
}


Output:




Comments

Popular Posts