So rather than
printf("%d\n", i);
How about
printf("%d +", i);
And then print just \n right at the end.
So rather than
printf("%d\n", i);
How about
printf("%d +", i);
And then print just \n right at the end.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
That will yield this...
6+
6+
28+
28+
28+
28+
496+
496+
496+
496+
496+
496+
496+
496+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
8128+
> That will yield this...
What utter tosh!
This is your code (before you decided to delete it and go in for some revisionist history), with the two single-line changes I mentioned.
Produces this outputCode:#include <stdio.h> int isperfect(int x) { int total=0,i=0; for (i=0;i<(x/2);i++) { if (!(x%(i+1))) { total+=i+1; } } if (total==x) return 1; return 0; } void print_perfect(int x) { int total=0,i=1; for (i=0;i<(x/2);i++) //!! copy/paste FAIL! { if (!(x%(i+1))) { printf("%d+", i+1); //!! Don't print a newline here //break; } } printf("\n"); //!! print it here // similar loop to that in isperfect, but instead of adding to total // you need to print every factor you find, with a + between them } int main(void) { int a=2,b=10000; for(; a<b; a++) if(isperfect(a)) print_perfect(a); return 0; }
Code:$ ./a.out 1+2+3+ 1+2+4+7+14+ 1+2+4+8+16+31+62+124+248+ 1+2+4+8+16+32+64+127+254+508+1016+2032+4064+
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Hey Salem, wow I have no idea what I was thinking. I think I was in kind of a daze last night from the long day. I swear calc 3, diff eq, physics, logic design, and this class are just burning me out! It sucks because this C class is kind of taking a back seat to the other classes because even though its good to know this code Im not going to be a programmer. Thanks for the help though, I just messed things up once I went back in and try to change everything!
ok well Im finished and everything works! Thanks for the help everyone..heres the code! Does spacing and everything look ok?
Code:#include <stdio.h> /* int isperfect(int x) { int total=0,i=0; for (i=0;i<(x/2);i++) { if (!(x%(i+1))) { total+=i+1; } } if (total==x) return 1; return 0; } void print_perfect(int x) { int total=0,i=0; printf("%4d = 1", x); for (i=1;i<(x/2);i++) { if (!(x%(i+1))) { printf(" + %d", i+1); } } printf("\n"); } int main(void) { int a=2,b=10000; for(; a<b; a++) { if(isperfect(a)) print_perfect(a); } return 0; }