题目描述
一个数如果恰好等于它的因子之和,这个数就称为"完数"。 例如,6的因子为1、2、3,而6=1+2+3,因此6是"完数"。 编程序找出N之内的所有完数,并按下面格式输出其因子:
输入
N
输出
? its factors are ? ? ?
样例输入
1000
样例输出
6 its factors are 1 2 3 28 its factors are 1 2 4 7 14 496 its factors are 1 2 4 8 16 31 62 124 248
此题用的暴力破解,在数据多的时候会爆,不过可以通过题目中的测试数据...
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int sum = 0;
int s[] = new int[1000];
int k = 0;
for (int j = 1; j < i; j++)
if (i % j == 0) {
sum += j;
s[k] = j;
k++;
}
if (sum == i) {
System.out.print(i + " its factors are ");
for (int l = 0; l < k; l++) {
System.out.print(s[l] + " ");
}
System.out.println();
}
}
}
}