I got this homework about perfect numbers between 1-1000, where a number equals to a sum of its divisors. I've found the right code to check if a number is a perfect number and found that those numbers were 1, 6, 28, 496 (I don't know why 1 is included but that was included in my teacher's example). My question is simple. The output I hoped for was something like:
1 = 1
6 = 1+2+3
28 = 1+2+4+7+14
496 = 1+2+4+8+16+31+62+124+248
but what I've managed to get was:
1 = 1
6 = 1+2+3+
28 = 1+2+4+7+14+
496 = 1+2+4+8+16+31+62+124+248+
How do I exclude the extra + in the end?
My code goes something like this:
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("");
}
}
}
}
Thanks in advance.
Since this is homework I'll just give a hint, which is, simply, only print the +
if it's not the first iteration of the loop. It's easy to test for that, I'll let you figure it out.
Edit, with an additional hint: you may need to experiment with where exactly you print the +
.