Home > other >  Trying to make factorial in React
Trying to make factorial in React

Time:10-24

I'm trying to make factorial in React but I don't know what's going on and the result doesn't appear correct.

I think there is something wrong when I tried to do a for-loop. When the input value is 0, 1 or 2, no result appears.

import React, {useState} from 'react';   

function Calculo_Do_Fatorial() {
    const [Dado, setdado] = useState('');
    const [resultado, setResultado] = useState();
    var fatorial = Dado;
    var primeiroMultipicador = Dado - 1;


function calcular () {

    if (Dado < 0) {
        let cheio = 'O valor de x deve ser igual ou maior que zero';
            setResultado(cheio)

    }if (Dado === 0 || Dado === 1) {
        let cheio1 = 1 ;
           setResultado(cheio1)

    }for (var i = primeiroMultipicador; i > 1; i--) {
        fatorial = fatorial*i;
   
        let cheio2 = fatorial;
            setResultado(cheio2);
    }
        
    }
  
    return (
        <div className='Calculo_Do_Fatorial'>
          <h1>Cálculo do Fatorial</h1><br></br>
          
  
              <div className="input">
                <label htmlfor="nome">Insira o número </label>
                <input type="number"  required="required" value={Dado} onChange={(e)=> setdado(e.target.value)}/>
              </div>  
                <button className="calcular1" id='calcular' onClick={calcular}>Calcular</button>
                <div className="result" id='resultado' >{typeof resultado === 'number' ? resultado.toFixed( 5 ).replaceAll(".", ",") : resultado}</div>  
        </div>
    );
}

export default Calculo_Do_Fatorial

I don't know what can be done to fix

CodePudding user response:

First, it's a better (in my own opinion) to name your useState() in a Edit trying-to-make-factorial-in-react

FYI, a functional method to compute the factorial could be:

const factorial = [...Array(dado).keys()]
  .map((i) => i   1)
  .reduce((factorial, i) => factorial * i, 1);

setResultado(factorial);

or

const factorial = Array.from({ length: dado }, (_, i) => i   1)
  .reduce((factorial, i) => factorial * i, 1);

setResultado(factorial);

Either creates an array of [1..n] and reduces it into a factorial value. The benefit here is that you don't need to handle 0 or 1 as specific cases.

Edit trying-to-make-factorial-in-react (forked)

CodePudding user response:

Here is a well-known one-line implementation of factorial using recursion

const factorial = n => n === 0 ? 1 : n * factorial(n - 1)
  • Related