Best factor calculation algorithm

Asked

Viewed 8,188 times

9

So I’m learning to develop in Java. The teacher asked me to develop a method for Factorial. And also show on the screen what is happening, for example:

3! = 3 X 2 X 1 = 6

In fact, I made it happen, but there is some way the code gets better?:

    int n = Integer.parseInt(txtN.getValue().toString());        
    int f = 1; 
    int c = n; 
    String s = ""; 

    while(c>=1){ 
        f *= c;
        if (c == 1) {
            s += c; 
        } else if (c>1) {
            s += c + " x " ;
        }
        c--;
    }

    lblFat.setText(s + " = " + Integer.toString(f));

The code generates the factorial and must also show the numbers on the screen.

Example

3! = 3 X 2 X 1 = 6
3! -> txtN (Local para o usuário inserir o número)
6 -> lblFat (local que gera o resultado)

Factorial in Java, has a better way of writing code?

  • You can use the Lanczos :D approach

5 answers

10


The most common is to separate the calculation from the presentation, but in something so simple you can understand. According to what was put in the question I would do so (actually I would probably use a for):

int f = 1; 
int c = n; 
String s = ""; 
while (c > 1) { 
    f *= c;
    s += c + " x " ;
    c--;
}
s += c;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

To do it recursively would be much more complicated, although it is not necessary.

Obviously using a simple integer there is a restricted limit of the maximum that can calculate the factorial. I believe that for this exercise this is no problem, the intention is not something of production but rather understand the functioning of the algorithm, but it is worth knowing that in certain cases a BigInteger would be better, as commented by Bruno Bermann.

  • Cool, it’s narrowed down a few lines of code and made it clearer.

  • Just complementing the answer: The factorial made in this way with integers is limited to the limit size of the variable (int = 2 31-1 = 2147483647). It is possible to do with long or with Bigintegers as well. The latter would virtually limit the size of the factor return only by the memory available in the system. To check the return when the value is exceeded do a test with the factorial of 100, for example.

2

public class calculeFatorial{
  public static void main(String[] args) {
    int fatorial = 1;

    for (int i = 1;i < 11 ; i ++ ) {
      fatorial *= i;

      System.out.println("Fatorial de " +i+"=" +fatorial);
    }
  }
}

1

Dude you can do recursive.

Int FatorialRecursivo(int num){

   If(num==1) || (num==o)
      return 1;
   else
      return FatorialRecursivo(n-1)*n;
 }

I’m sorry the half messed up code I’m answering by APP, anything asks if you don’t understand the recursion.

  • 2

    Your code works, but it’s not suitable for large factors, considering the overhead that recursion generates and the impending stack overflow problem.

  • @Brunobermann actually works for something other than what was asked in the question. This is a generic factorial. I didn’t mean to be negative, but it doesn’t answer what was asked.

  • @Bigown You are right, the code does not contemplate what was asked in the question, considering the whole. Yet it exemplifies a different way of calculating factorial. I commented on both answers (yours and Nathan’s) to highlight the problems that can occur in both algorithms, in case someone who reads in the future decides to use some of them in some more "demanding" software, let’s say so.

  • 1

    The algorithm can even work, the code doesn’t. It doesn’t exist Int and If in Java. And the condition (num==1) || (num==0) would never work if it wasn’t grouped by a (...).

  • 3

    @The code and the algorithm, according to the question, are wrong, yet received 3 votes, It is what we always speak of the vote given automatically without content analysis..

1

Introducing Factoriais com for:

long fat=1;
String mult="";
for (int i=5; i>1; i--){
    fat *=i;
    mult +=i+" x ";
}
System.out.print(mult+"1 = "+fat);

See rotating on Ideone

It is more recommended that the variable that accumulates the values be of the long type, considering that the int has greater spectrum limitation. To change the value, just change the 5 for a variable and choose how to feed it.

At the end, 1 was added outside the repeating structure. Because it is factorial, the multiplication is not affected by it, being able to remove it, saving a turn in the calculations, only being aggregated in the string that had already received the " X " after the 2.

-3

public int metodo(int valor){

        if(valor==1)
           return 1;

        else

         return (valor * metodo(valor -1)); //desmontando o numero 
               
    }
// UTLIZANDO RECURSIVIDADE
  • Explain your answer better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.