0

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.

false
  • 10,264
  • 13
  • 101
  • 209

2 Answers2

1

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 +.

musical_coder
  • 3,886
  • 3
  • 15
  • 18
  • the other answer spoiled it (well, not completely) for me. if the j==1, I only printed j, otherwise I printed +j.. Thanks for the hints. – Wildan Maulana Syahidillah Nov 25 '13 at 23:28
  • No problem, glad it worked. I'm an ex-teacher, so I like to just give hints if possible, but most of the time people will write out the code for you. For the future, if you explicitly ask just for hints in your post, I think most people will respect that. – musical_coder Nov 25 '13 at 23:37
0

try this

boolean first = true;
for(int j=1;j<i;j++){
     if(i%j==0)
        if(!first)
           System.out.print("+"+j);
        else{
           first = false;
           System.out.print(j);
        }
 }
subash
  • 3,116
  • 3
  • 18
  • 22