Project Euler #74: Digit factorial chains

  • + 0 comments

    java

    public class Solution {

    public static void main(String[] args) {
        // factorial of digits from 1 to 9
        int [] fact = {1,1,2,6,24,120,720,5040,40320,362880};
    
        ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
    
        for(int i=0;i<=60;i++) arr.add(new ArrayList<Integer>());
    
        for(int i = 0;i<=1000000;i++){
    
            // to check i has loop as defined in problem statement 
            HashSet<Long> h = new HashSet<Long>();
            long fsum = i;
            String s = ""+i;
            int len = 0;
            while(h.contains(fsum) == false){
                h.add(fsum);
                fsum = 0;
                len++;
                if(len>60) break;
                // to cal sum of factorial of digits
                for(int j = 0;j<s.length();j++) fsum += fact[s.charAt(j)-'0'];
                s = ""+fsum;
            } 
            if(len<=60)
               arr.get(len-1).add(i);
        }
        // output according to test case
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while(t-- != 0){
            int num = sc.nextInt(),l = sc.nextInt();
            int c = 0;
            for(Integer i: arr.get(l-1)){
                if(i<=num) {
                    System.out.print(i + " ");
                    c++;
                }
                else break;
            }
            if(c == 0) System.out.print(-1);
            System.out.println();
        }
    
    }
    

    }