|

楼主 |
发表于 2011-7-6 20:47:33
|
显示全部楼层
题目分析:由于亲密数是两个数之间的关系。也就说,不能立刻判断一个整数A是否有亲密数,更不知道它的亲密数是多少。因此,在算法的选择上,我采用了一种具有选择性质的算法来查找一定范围内的亲密数,此算法效率不高,但直观有效。
在一个数集{ a1, a2, a3,..........., an }中寻找亲密数,可以针对某一个元素,在其他的元素中寻找该元素的亲密数。这样即划分两个集合:A、B;最初数集中所有的元素都放在集合B中,然后从B中任意选择一个元素放入集合A中,同时在集合B中删去该元素。然后在集合B中的其他元素中寻找刚刚放入集合A中的那个元素的亲密数。
重复上述过程,直到B集合为空。
- #include "stdio.h"
- int factorSum( int elem_a ) //求a的因子和
- {
- int i, sum = 0;
- for( i = 1; i < elem_a; i++ )
- {
- if( elem_a % i == 0 )
- sum = sum + i;
- }
- return sum;
- }
- int isfriend( int elem_a_factor, int elem_b_factor, int elem_a, int elem_b ) //判断A、B两个数是否是完全数其中elem_a、elem_b分别是A、B;elem_a_factor、elem_b_factor 分别是A的因数和、B的因数和
- {
- if( elem_a_factor == elem_b && elem_b_factor == elem_a )
- return 1;
- else
- return 0;
- }
- void friendly( void )
- {
- int elem_a, elem_b, temp[3001];
- for( elem_a = 1; elem_a <= 3000; elem_a++ )
- temp[elem_a] = factorSum(elem_a);
- for( elem_a = 1; elem_a <= 3000; elem_a++ )
- {
- if( temp[elem_a] != -1 )
- {
- for( elem_b = elem_a + 1; elem_b <= 3000; elem_b++ )
- {
- if( isfriend( temp[elem_a], temp[elem_b], elem_a, elem_b ) )
- {
- printf("(%d,%d) ",elem_a,elem_b);
- temp[elem_b] = -1;
- }
- }
- }
- }
- }
- int main()
- {
- printf("There are following friendly numbers from 1 to 30000\n");
- friendly();
- printf("\n");
- return 0;
- }
复制代码
|
|