一个数如果恰好等于它的因子之和,这个数就称为「完数」。例如 6=1+2+3.编程找出 1000 以内的所有完数。

public class Tl5 {
	/**
	 * 判断是否是完数
	 * @param a 需判断的数字
	 * @return boolean
	 */
	public static boolean test(int a) {
		int cup = 0;
		// 循环遍历,找到所有因子,并计算因子之和
		for (int i = 1; i < a; i++) {
			if (a % i == 0)
				cup = cup + i;
		}
		return (cup == a);
	}

	public static void main(String[] args) {
		String str = "";
		for (int i = 1; i < 1000; i++) {
			if (test(i)) {
				str += i + ",";
			}
		}
		System.out.print(str.substring(0, str.length() - 1));
	}
}

猜你喜欢

转载自blog.csdn.net/axiba01/article/details/80964604