Search code examples
javamathfactorial

Doing a factorial with only one while loop


I'm trying to find the factorial of 9 down to 0, only using one while loop, but my idea isn't outputting a value.

I figured out the way to do it using two while loops:

    int i;
    count = 9;
    while (count >= 0){
        value = count;
        i = count-1;
        while (i > 0){
            value = value * i;
            i--;
        }
        System.out.print(value + ", ");
    }

This worked but I've tried to change it to use only one while loop and got this:

    int i;
    for (count = 9; count < 0; count--){
        value = count;
        i = count-1;
        while (i > 0){
            value = value * i;
            i--;
        }
        System.out.print(value + ", ");
    }

I'm not completely sure if I'm using the for statement correctly but I think I am, or at least I think it should output something so I can debug it.

Could someone give me a hint in the right direction?


Solution

  • This will give you all the factorials from 9 down to 1 :

    int i=1;
    int value=1;
    String res = "";
    while (i <= 9){
      value = value * i;
      res = value + ((i>1)?",":"") + res;
      i++;
    }
    System.out.print(res);
    

    Output :

    362880,40320,5040,720,120,24,6,2,1
    

    Perhaps it's cheating, since I'm calculating the factorials in ascending order from 1! to 9!, but I'm reversing the order of the output in order to get the required result.

    Edit :

    If you also want 0! to be printed, a small change can do the trick :

    int i=1;
    int value=1;
    String res = "";
    while (i <= 10){
      res = value + ((i>1)?",":"") + res;
      value = value * i;
      i++;
    }
    System.out.print(res);
    

    Output :

    362880,40320,5040,720,120,24,6,2,1,1