- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- /**
- * 真因子算法 除了自己 所有能被自己整除的正数相加等于自己本身
- */
- List<Integer> answer = new ArrayList<Integer>();
- for (int max = 10000; max > 1; max--) {
- int temp[] = new int[max];
- int index = 0;
- int result = 0;
- for (int i = 1; i < max; i++) {
- int c = max % i;
- if (c == 0) {
- temp[index] = i;
- index++;
- // System.out.println(i);
- }
- }
- for (int i = 0; i < temp.length; i++) {
- result = result + temp[i];
- }
- if (result == max) {
- answer.add(max);
- }
- // System.out.println("---------------------------------");
- }
- for (int i = 0; i < answer.size(); i++) {
- int num = answer.get(i);
- System.out.println(num);
- }
- Integer[] s=answer.toArray(new Integer[0]);
- /**
- * 有两个数组a,b,大小都为n,数组元素的值任意,无序; 要求:通过交换a,b中的元素,使数组a元素的和与数组b元素的和之间的差最小
- */
- int n = 10;
- int a[] = { 231, 331, 41, 3123, 45, 66, 752, 25, 135, 20 };
- int b[] = { 21, 2, 41, 313, 453, 66, 1752, 25, 5, 15 };
- int totala = 0;
- int totalb = 0;
- int distance;
- int aminIndex = 0;
- int bminIndex = 0;
- for (int i = 0; i < n; i++) {
- totala = totala + a[i];
- totalb = totalb + b[i];
- }
- boolean transform = false;
- System.out.println("數組A的和:" + totala);
- System.out.println("數組B的和:" + totalb);
- distance = totala - totalb;
- if (distance == 0) {
- System.out.println("int a[]=int b[]");
- } else {
- if (distance < 0) {
- int temp[] = a;
- a = b;
- b = temp;
- distance=Math.abs(distance);
- transform = true;
- }
- int min = totala;
- int j;
- for (j = 0; j < n; j++) {
- int k = 0;
- while (k < n) {
- int change = a[j] - b[k];
- if ((2 * change) == distance) {
- int temp = a[j];
- a[j] = b[k];
- b[k] = temp;
- break;
- } else {
- if (change > 0&& (Math.abs((2 * change) - distance) < min)) {
- min = Math.abs((2 * change) - distance);
- aminIndex = j;
- bminIndex = k;
- }
- k++;
- }
- }
- }
- if (transform == true) {
- System.out.println("數組A中值为:" + b[bminIndex ]+",下标为"+bminIndex +
- "的数与數組B中值为:"+ a[aminIndex ]+",下标为"+aminIndex+ "的数互换,數組A与 B的差最小");
- } else {
- System.out.println("數組A中值为:" + a[aminIndex ]+",下标为"+aminIndex +
- "的数与數組B中值为:"+ b[bminIndex ]+",下标为"+bminIndex+ "的数互换,數組A与 B的差最小");
- }
- }
- }
- }