【发布时间】:2014-06-18 20:55:19
【问题描述】:
我的作业是关于 1-1000 之间的完美数字,其中一个数字等于它的除数之和。我找到了正确的代码来检查一个数字是否是一个完美的数字,并发现这些数字是 1、6、28、496(我不知道为什么要包含 1,但我老师的示例中包含了)。我的问题很简单。我希望的输出类似于:
1 = 1
6 = 1+2+3
28 = 1+2+4+7+14
496 = 1+2+4+8+16+31+62+124+248
但我设法得到的是:
1 = 1
6 = 1+2+3+
28 = 1+2+4+7+14+
496 = 1+2+4+8+16+31+62+124+248+
最后如何排除多余的+?
我的代码是这样的:
private static boolean perfect(int n){
boolean cek=false;
int x=0;
if(n==1)x=1;
for(int i=1;i<n;i++){
if(n%i==0)
x+=i;
}
if(x==n)cek=true;
return cek;
}
public static void main(String[] args) {
for(int i=1;i<1000;i++){
if(perfect(i)){
if(i==1)
System.out.println(i+"\t = "+i);
else{
System.out.print(i+"\t = ");
for(int j=1;j<i;j++){
if(i%j==0)
System.out.print(j+"+");
}
System.out.println("");
}
}
}
}
提前致谢。
【问题讨论】:
-
你真的需要每次都检查
if (i==1)吗? -
哈哈哈不,我猜这有点低效。我本来可以一开始就打印出来的。
-
是的,我会解决的
标签: java formatting perfect-numbers