1

i have been asked to create a program which will receive a number and take 1 away each loop until it reaches 0 and then output each number and multiply them

e.g if the user enters 5 the output should be

5*4*3*2*1=120

i tried the following with no luck

int factor = sc.nextInt();
    int count = 0;
    int total = factor;
    StringBuilder answer = new StringBuilder();
    answer.append(factor);
    while(factor>0)
    {

        for(int i = factor; i >= 0; i--)
        {
           count++;
           total = total*count;
           total = total -1;
           if(i==factor)
           {
               answer.append(" = ").append(total);
           }
           else
           answer.append(" * ").append(String.valueOf(i));
        }

    }
    int sanswer=Integer.parseInt(answer.toString());
    return sanswer;
}

2 Answers2

0

Actually it is task for factorial calculation. You can find a various of realization here

If you don't want to use recursion:

int factorial ( int input )

  int x, fact = 1;
  for ( x = input; x > 1; x--)
     fact *= x;

  return fact;
Grushman
  • 41
  • 4
  • i know how to do this the reason i tried it the other way is because of the way the answer needs to be displayed because it needs to be returned like e.g. 5*4*3*2*1=120 – studentprogrammer Nov 23 '16 at 17:27
0

First with each iteration append the number i looped. Then decide to append * or finally = based on if the following iteration is the final one. After printing =, there remains only to print the result number. You cannot onvert the String to int, easily if it contains not-digit characters.

Try the following code:

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
long factorial = 1L;
StringBuilder answer = new StringBuilder();

for (int i=num; i>0; i--) {
    answer.append(i);
    if (i-1>0) {
        answer.append("*");
    } else {
        answer.append("=");
    }
    factorial *= i;
}
answer.append(factorial); 
System.out.println(answer);

Input: 8. Output: 8*7*6*5*4*3*2*1=40320.

Input: 5. Output: 5*4*3*2*1=120.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183