0

so I have this code:

int in = 496;
boolean b = true; 
Sting s = "": 

if (b) {
        int test = 0;

        System.out.print(in + ":");

        for (int i = 1; i < in; i++) {
            if (in % i == 0) {
                test += i;
                s += i + " ";
            }
        }
        System.out.println(" ");
    } else {
        System.out.println(in + " no factorials");
    } 

and it prints like this:

496:1 2 4 8 16 31 62 124 248

but I want to revers the factorials output to look like this:

496:248 124 62 31 16 8 4 2 1

I tried to reverse the for loop, but it work, so any ideas guys?

4
  • Look here: stackoverflow.com/questions/2441501/… Commented Apr 7, 2014 at 17:43
  • Show us the code where you reversed the loop. Commented Apr 7, 2014 at 17:43
  • 1
    I see =+ Did you mean += ? Commented Apr 7, 2014 at 17:44
  • I did try in the for loop this: for (int i = in; i >= 0; i--) and it didn't work, but I see that @Bart answer works. Commented Apr 7, 2014 at 17:59

2 Answers 2

2

Changing the loop is indeed what you'd need:

for (int i = in-1; i > 0; i--) {

By the way, how did you post your code? What you pasted (or typed) does not print any factorials, and s =+ ... should probably be s += ..., right? Please be as concise as possible, so we have to guess/correct only the real problem, not any typos.

Sign up to request clarification or add additional context in comments.

2 Comments

Bart just beat me to it. that's all I changed in my answer.
yes the =+ was a typo and using this method works!
0

Untested, but why won't this work?

int in = 496;
boolean b = true; 
Sting s = "": 

if (b) {
    int test = 0;

    System.out.print(in + ":");

    for (int i = in-1; i > 0; i--) {
        if (in % i == 0) {
            test += i;
            s =+ i + " ";
        }
    }
    System.out.println(" ");
} else {
    System.out.println(in + " no factorials");
} 

also, it would help everyone if you used better variable names... once your methods get a bit more complicated it'll be hard to follow 's', 'b', 'i', and even 'in'.

1 Comment

there was a typo in the line s += i + " "; where it should s += i + " "; and my apologies I tried to make this code very short since it's just a test code to a larger program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.