Open In App

Find minimum number X such that sum of factorial of its digits is N

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to find the minimum number X such that A(X) = N, where A(X) for positive integer X is the sum of factorials of its digits. For example, A(154) = 1! + 5! + 4!= 145. Return a list of digits which represent the number X.

Example:

Input: N = 40321
Output: 18
Explanation: A(18) =1! + 8!  = 40321. Note that A(80) and A(81) are also 40321, But 18 is the smallest number.

Input: N = 5040
Output: 7

Approach: To solve the problem follow the below idea:

For any digit n, n! can be written as n * ((n – 1)!). So, digit n – 1 is required exactly n times. This means that taking smaller numbers when a larger number can be taken will just increase the number of digits in our final answer. So, use the greedy approach and subtract the largest value of n! from N until N becomes 0.

Follow the steps to solve this problem:

  • Make a factorial array and put all factorials ranging from 0 to 9 in it. 
  • Keep a variable i and initialize it to 9. 
  • Now run a while loop and check if factorial[i] <= N. 
  • Now run another while loop and check how many times you can put subtract factorial[i] from N. Do this for i from 9 to 1. 
  • Now simply reverse the vector to get the smallest possible number.

Below is the implementation of this approach:

C++




// C++ code to implement this approach
#include <bits/stdc++.h>
using namespace std;
 
// fact will store values of factorials from 0 to 9
vector<int> fact;
 
// ans will have final digits of number obtained X
vector<int> ans;
 
// Helper function to solve the problem
int helper(int N)
{
    if (N == 0)
        return 1;
    else if (N < 0)
        return 0;
    for (int i = 9; i >= 0; i--) {
        if (fact[i] > N)
            continue;
        ans.push_back(i);
        int d = helper(N - fact[i]);
        if (d == 1)
            return 1;
        ans.erase(find(ans.begin(), ans.end(), i));
    }
    return 0;
}
 
// Function to find the smallest number
// sum of factorials of whose digits = N
vector<int> FactDigit(int N)
{
    fact.assign(10, 1);
    fact[0] = fact[1] = 1;
    for (int i = 2; i <= 9; i++)
        fact[i] = i * fact[i - 1];
    helper(N);
    sort(ans.begin(), ans.end());
    return ans;
}
 
// Driver Code
int main()
{
    int N = 40321;
 
    // Function call
    vector<int> ans = FactDigit(N);
    for (auto i : ans)
        cout << i;
    return 0;
}


Java




// Java code to implement this approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // fact will store values of factorials from 0 to 9
  static List<Integer> fact = new ArrayList<Integer>(10);
 
  // ans will have final digits of number obtained X
  static List<Integer> ans = new ArrayList<Integer>();
 
  // Helper function to solve the problem
  static int helper(int N)
  {
    if (N == 0)
      return 1;
    else if (N < 0)
      return 0;
    for (int i = 9; i >= 0; i--) {
      if (fact.get(i) > N)
        continue;
      ans.add(i);
      int d = helper(N - fact.get(i));
      if (d == 1)
        return 1;
      ans.remove(ans.get(i));
    }
    return 0;
  }
 
  static List<Integer> FactDigit(int N)
  {
    fact.add(1);
    fact.add(1);
    for (int i = 2; i <= 9; i++) {
      fact.add(i * fact.get(i - 1));
    }
    helper(N);
    Collections.sort(ans);
    return ans;
  }
 
  public static void main(String[] args)
  {
    int N = 40321;
 
    // Function call
    List<Integer> ans = FactDigit(N);
    for (int i = 0; i < ans.size(); i++) {
      System.out.print(ans.get(i));
    }
  }
}
 
// This code is contributed by lokeshmvs21.


Python3




# Python code to implement this approach
 
# fact will store values of factorials from 0 to 9
fact = []
 
# ans will have final digits of number obtained X
ans = []
 
# Helper function to solve the problem
def helper(n)->int:
    if(n == 0):
        return 1
    elif(n<0):
        return 0;
    i = 9
    while(i>=0):
        if(fact[i] > n):
            i -= 1
            continue
        ans.append(i)
        d = helper(n-fact[i])
        if(d==1):
            return 1
        while(i in ans):
            ans.remove(k)
        i -= 1
    return 0
   
# Function to find the smallest number
# sum of factorials of whose digits = N
def FactDigit(n):
    fact.append(1)
    fact.append(1)
    for i in range(2,10):
        fact.append(i*fact[i-1])
    helper(n)
    ans.sort()
    return ans
 
# Driver Code
if __name__ == '__main__':
    n = 40321
     
    # Function call
    answer = FactDigit(n)
    for i in answer:
        print(i, end='')
         
        # This code is contributed by ajaymakvana.


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  // fact will store values of factorials from 0 to 9
  static List<int> fact = new List<int>(10);
 
  // ans will have final digits of number obtained X
  static List<int> ans = new List<int>();
 
  // Helper function to solve the problem
  static int helper(int N)
  {
    if (N == 0)
      return 1;
    else if (N < 0)
      return 0;
    for (int i = 9; i >= 0; i--) {
      if (fact[i] > N)
        continue;
      ans.Add(i);
      int d = helper(N - fact[i]);
      if (d == 1)
        return 1;
      ans.Remove(ans[i]);
    }
    return 0;
  }
 
  static List<int> FactDigit(int N)
  {
    fact.Add(1);
    fact.Add(1);
    for (int i = 2; i <= 9; i++) {
      fact.Add(i * fact[i - 1]);
    }
    helper(N);
    ans.Sort();
    return ans;
  }
 
// Driver Code
public static void Main()
{
    int N = 40321;
 
    // Function call
    List<int> ans = FactDigit(N);
    for (int i = 0; i < ans.Count; i++) {
      Console.Write(ans[i]);
    }
}
}
 
// This code is contributed by sanjoy_62.


Javascript




// JavaScript code to implement this approach
 
// fact will store values of factorials from 0 to 9
const fact = [];
 
// ans will have final digits of number obtained X
const ans = [];
 
// Helper function to solve the problem
function helper(n) {
  if (n === 0) {
    return 1;
  } else if (n < 0) {
    return 0;
  }
  let i = 9;
  while (i >= 0) {
    if (fact[i] > n) {
      i -= 1;
      continue;
    }
    ans.push(i);
    const d = helper(n - fact[i]);
    if (d === 1) {
      return 1;
    }
    while (ans.includes(i)) {
      ans.splice(ans.indexOf(i), 1);
    }
    i -= 1;
  }
  return 0;
}
 
// Function to find the smallest number
// sum of factorials of whose digits = N
function factDigit(n) {
  fact.push(1);
  fact.push(1);
  for (let i = 2; i < 10; i++) {
    fact.push(i * fact[i - 1]);
  }
  helper(n);
  ans.sort();
  return ans;
}
 
// Driver Code
const n = 40321;
 
// Function call
const answer = factDigit(n);
console.log(answer.join(''));
 
// This code is contributed by shivamsharma215


Output

18

Time Complexity: O(log(N))
Auxiliary Space: O(1), since we are only making a single factorial vector of size 10



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads