How to do a factorial for my calculator [closed]

0

I'm doing a scientific calculator. This calculator has several mathematical functions for the number entered. For example, in this code the square root is calculated:

if (e.getSource() == boton[11]) {
    if (!entrada.equals("") && !entrada.equals("0")) {
        double valor = Double.parseDouble(entrada);
        valor = Math.sqrt(valor);
        entrada = "" + valor;
    }
}

What I need is to show the result of the factorial calculation in the following code:

if( e.getSource() == boton[3]) {
    double valor = Double.parseDouble(entrada); 
    //qué hacer
}

Would someone help me please?

    
asked by Ely 17.03.2016 в 17:56
source

4 answers

1

Assuming you have a method called factorial defined in the following way (or similar):

private long factorial(long n) {
    /* código del método factorial */
}

You can do the following:

if( e.getSource() == boton[3]) {
    long valor = Long.parseLong(entrada);
    entrada = String.valueOf(factorial(valor));
}
    
answered by 17.03.2016 в 18:12
1
  

Remembering that the factorial of a number is the result that is   get multiplied that number by the previous one and so   successively until you reach one.

My answer is using the recursion and return value long to avoid overflows.

long factorial(int x) {
    return (x == 0) ?  1 : x * factorial(x-1);
}

Link of interest: Link

    
answered by 28.03.2016 в 21:31
0

Contributing a grain of sand using recursion:

public int factorial(int numero)
{
   int resultado;
   if(numero==0 || numero==1)
     return 1;

   resultado = factorial(numero-1) * numero;
   return resultado;
}
    
answered by 28.03.2016 в 20:10
0
  

Maybe this can help you:

    public int factorial(int numero){
      int factorial=1;
      for(int i=1,i<=numero;i++){
        factorial=i*factorial;
      }
      return factorial;
    }
    
answered by 28.03.2016 в 19:24