刚好写了一个,楼上的,如果有十万个数,你就定义一个长度十万的数组?一百万呢?- int num1 = 0;
- int num2 = 0;
- int a = 0;
- int b = 0;
- string tmp = "";
- int count = 0;
- string[] result = null;
- for (int i = 1; i <= 3000; i++) {
- a = i;
- for (int j = 1; j < i; j++) {
- if (i % j == 0) {
- //i的因子和
- num1 += j;
- }
- b = num1;
- }
- //Console.WriteLine(num1.ToString());
- for (int k = 1; k < num1; k++) {
- if (b % k == 0) {
- //b的因子和
- num2 += k;
- }
- }
- //a的因子和等于b,b的因子和等于a,且a不等于b
- if (num1 == b && num2 == a && a!=b)
- {
-
-
- tmp += a + "," + b+",";
- }
- num1 = 0;
- num2 = 0;
- }
- //算出有几对亲密数
- for (int i = 0; i < tmp.Length; i++) {
- if(tmp.Substring(i,1)==","){
- count++;
- }
- }
- //new一个数组存放结果
- result = new string[count];
- count = 0;
- for (int i = 0; i < tmp.Length; i++) {
- //读取字符串,如果是逗号,标记自加
- if(tmp.Substring(i,1)==","){
- count++;
- }
- //否则将当前字符加入数组当前位置
- else {
- result[count] += tmp.Substring(i, 1);
-
- }
- }
- //输出1和3,5和7,以此类推
- for (int i = 0; i < result.Length-2; i++) {
- if (i % 2 != 0) {
- Console.WriteLine("{0}和{1}是亲密数",result[i],result[i+2]);
- i = i + 2;
- }
-
- }
- Console.ReadKey();
-
复制代码 |