Search code examples
javafactorial

Simplifying Factorial


This is my code for displaying factorial. But I think it's too long. How can I make my code shorter? Feedback will be appreciated. Thank you!

This is the sample output:

6! = 5*4*3*2*1 = 720

This is my code:

import java.io.*;
public class Factorial {

   public static void main (String args[]) throws IOException
   {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int f = 1;

System.out.print("Enter number: ");
int num = Integer.parseInt(br.readLine());
int temp3 = num;
String temp [] = new String [num];

while (num >= 1)
{
    f = num * f;
    num = num - 1;
}

   for (int x=1; x<temp3; x++)
   {
    temp[x]= "" + Integer.toString(x);
   }


StringBuffer result = new StringBuffer();
for (int i = temp3 - 1; i >= 1; i--) {
    result.append(temp[i]);

    if (i > 1)
    {
        result.append("*");
    }

}

   System.out.print(temp3 + "! = " + result.toString() + " = " + f);

   }


}

Solution

  • Rather than making your code shorter, focus on readability

    Some things that you need to fix before making it shorter

    1. Indendation
    2. Variable naming: temp, x, f etc. do not make sense
    3. Using correct data types: int will cause an overflow

    Also try to write code yourself rather than copying snippets

    for (int i = temp3 - 1; i >= 1; i--) {
        result.append(temp[i]);
    
        if (i > 1)
        {
    

    As far as I understand, there are 2 types of people in this world

    1. Who start the curly braces on the same line as the condition
    2. Who start on the next line

    How can you use both within a gap of 3 lines?