两个亲密数是指两个数的因子之和等于对方。
比如
220的因子之和为:1+2+4+5+10+11+20+22+44+55+110=204
204的因子之和为:1+2+4+71+142=220
又比如:1184和1210
源代码如下:
#include <iostream>
#include <cmath>
using namespace std;
int friendnum(int);
int ga[100],gb[100];
int main()
{
int i,b,length,count = 0;
length = 5000;
cout<<"列举1到"<<length<<"之间的所有亲密数对 "<<endl;
for (i = 0; i < length; i++)
{
b = friendnum(i);
if (b != 0)
{
cout<<i<<"--"<<b<<endl;
cout<<ga[0];
count = 1;
while (ga[count]>0)
{
cout<<" + "<<ga[count];
count++;
}
cout<<" = "<<b<<endl;
cout<<b<<"各因子之和为:";
cout<<gb[0];
count = 1;
while (gb[count]>0)
{
cout<<" + "<<gb[count];
count++;
}
cout<<" = "<<i<<endl;
}
}
system("pause");
return 0;
}
int friendnum(int a)
{
int i,b1,b2,count;
for (i = 0; i < 100; i++)
{
ga[i] = gb[i] = 0;
}
count = 0;
b1 = 0;
for (i = 1; i < a;i++)
{
if (a%i == 0)
{
ga[count++] = i;
b1 += i;
}
}
count = 0;
b2 = 0;
for (i = 1;i < b1; i++)
{
if (b1%i == 0)
{
gb[count++] = i;
b2 += i;
}
}
if (b2 == a&& a < b1)
{
return b1;
}
else
return 0;
}
结果: