OneCompiler

rectify the Time error

import java.util.*;

public class Main {

// Precomputed factorials for digits 0-9
private static final int[] FACTORIALS = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};

// Function to calculate the sum of factorials of the digits
public static int sumOfFactorialDigits(int num) {
    int sum = 0;
    while (num > 0) {
        sum += FACTORIALS[num % 10]; // Add precomputed factorial
        num /= 10; // Remove last digit
    }
    return sum;
}

// Function to determine the length of the unique sequence before repetition
public static int uniqueFactorialChainLength(int n) {
    HashSet<Integer> seenNumbers = new HashSet<>(); // Track visited numbers
    int length = 0;

    while (!seenNumbers.contains(n)) {
        seenNumbers.add(n); // Store the number
        n = sumOfFactorialDigits(n); // Compute next number
        length++;
    }

    return length;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt(); // Read input number
    System.out.println(uniqueFactorialChainLength(n)); // Print only the final output
    scanner.close();
}

}

No answers yet!

1 year ago by