完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。
它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。
例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。
给定函数count(int n),用于计算n以内(含n)完全数的个数。计算范围, 0 < n <= 500000
返回n以内完全数的个数。异常情况返回-1
输入一个数字
输出完全数的个数
1000
3
import java.util.Scanner;
/**
* Author: 王俊超
* Date: 2015-12-24 19:58
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
int n = scanner.nextInt();
System.out.println(count(n));
}
scanner.close();
}
private static int count(int n) {
int result = 0;
for (int i = 2; i < n; i++) {
int sum = 1;
int sqrt = i / 2;
for (int j = 2; j <= sqrt; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
result++;
}
}
return result;
}
}
原文:http://blog.csdn.net/derrantcm/article/details/51360110