1
resposta

[Sugestão] Duas formas de se obter o fatorial de um número

Este código serve como uma exemplificação de duas maneiras distintas de obter o fatorial de um número qualquer: uma utilizando recursividade e outra de forma mais genérica com variáveis locais. Há também outras abordagens, como o uso de BigDecimal, já que o fatorial cresce muito rapidamente.

Método sem recursividade:

@Contract(pure = true)
    private static long factorial(int n) {
        long n1 = 1;
        for (int i = 1; i <= n; i++) {
            n1 *= i;
        }
        return n1;
    }

Método recursivo + cache de memória:

@Contract(pure = true)
    private static long factorialRecursive(int n) {
        if (n <= 1) return 1;

        if (cache.containsKey(n)) return cache.get(n);

        long result = n * factorialRecursive(n - 1);
        cache.put(n, result);
        return result;
    }

Projeto completo

package com.github.rickmvi.challenge04;

import com.github.rickmvi.jtoolbox.console.Out;
import com.github.rickmvi.jtoolbox.console.utils.ScannerUtils;
import org.jetbrains.annotations.Contract;

import java.util.HashMap;
import java.util.Map;

public class Factorial {

    /**
     * A static cache to store precomputed factorial values to optimize
     * recursive calculations and prevent redundant computations during the
     * execution of the factorialRecursive method.
     * <p>
     * The cache maps an integer (representing the input) to its corresponding
     * factorial value as a long. It is used for memoization to improve performance
     * by reducing the time complexity of repeated factorial calculations.
     */
    private static final Map<Integer, Long> cache = new HashMap<>();

    public static void main(String[] args) {
        ScannerUtils.init();

        Out.printLine("Enter the amount of steps: ");
        int steps = ScannerUtils.nextInt();

        Out.printFormatted("Factorial Recursive: {}%n", factorialRecursive(steps)); // Utilize cache/memoization
        Out.printFormatted("Factorial: {}%n", factorial(steps));
        ScannerUtils.close();
    }

    /**
     * Calculates the factorial of a given non-negative integer using an iterative approach.
     *
     * @param n the non-negative integer for which the factorial is to be computed.
     *          Must be greater than or equal to 0.
     * @return the factorial of the input number as a long. Returns 1 if the input is 0 or 1.
     */
    @Contract(pure = true)
    private static long factorial(int n) {
        long n1 = 1;
        for (int i = 1; i <= n; i++) {
            n1 *= i;
        }
        return n1;
    }

    /**
     * Calculates the factorial of a given non-negative integer using a recursive approach.
     * This method uses memoization to optimize performance by storing previously
     * computed results in a static cache.
     *
     * @param n the non-negative integer for which the factorial is to be computed.
     *          Must be greater than or equal to 0.
     * @return the factorial of the input number as a long. Returns 1 if the input is 0 or 1.
     */
    @Contract(pure = true)
    private static long factorialRecursive(int n) {
        if (n <= 1) return 1;

        if (cache.containsKey(n)) return cache.get(n);

        long result = n * factorialRecursive(n - 1);
        cache.put(n, result);
        return result;
    }
}

Saida:
Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Espero que ajude alguém que tenha dúvida de como se faz, e dê um norte.

1 resposta

Oi, Rick! Como vai?

Parabéns por compartilhar sua solução para o desafio! É sempre interessante ver como as pessoas abordam o mesmo problema e desenvolvem suas próprias soluções.

Continue explorando e experimentando diferentes abordagens, isso é essencial para o crescimento no campo da programação!

Alura Conte com o apoio da comunidade Alura na sua jornada. Abraços e bons estudos!