Project Euler #254: Sums of Digit Factorials

  • + 0 comments

    IN JAVA BY: TANUSHREE SARKAR

    import java.util.Scanner;
    
    public class Solution {
        public static int f(int num) {
            int fact = num;
            if (num == 0) {
                fact = 1;
            } else {
                for (int i = num - 1; i > 0; --i) {
                    fact = fact * i;
                }
            }
            return fact;
        }
    
        public static int fn(int n) {
            int sum_f = 0;
            String temp = String.valueOf(n);
            for (int i = 0; i < temp.length(); ++i) {
                int conv_i = temp.charAt(i) - '0';
                sum_f += f(conv_i);
            }
            return sum_f;
        }
    
        public static int sfn(int num) {
            int sum_fn = 0;
            int sum_f = fn(num);
            String temp = String.valueOf(sum_f);
            for (int i = 0; i < temp.length(); ++i) {
                int conv_i = temp.charAt(i) - '0';
                sum_fn += conv_i;
            }
            return sum_fn;
        }
    
        public static int gi(int num) {
            int sum_fn;
            int i = 0;
            while (true) {
                ++i;
                sum_fn = sfn(i);
                if (num == sum_fn) {
                    break;
                }
            }
            return i;
        }
    
        public static int sgi(int num) {
            int sum_gi = 0;
            for (int i = 1; i <= num; ++i) {
                int temp = gi(i);
                if (temp < 10) {
                    sum_gi += temp;
                } else {
                    String s_temp = String.valueOf(temp);
                    for (int j = 0; j < s_temp.length(); ++j) {
                        int conv_i = s_temp.charAt(j) - '0';
                        sum_gi += conv_i;
                    }
                }
            }
            return sum_gi;
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int q = scanner.nextInt();
            for (int i = 0; i < q; ++i) {
                int n = scanner.nextInt();
                int m = scanner.nextInt(); // not used in the code
                System.out.println(sgi(n));
            }
        }
    }