# Minimum number of palindromes required to express N as a sum | Set 1

• Difficulty Level : Medium
• Last Updated : 08 Aug, 2022

Given a number N, we have to find the minimum number of palindromes required to express N as a sum of them.
Examples:

Input: N = 11
Output:
11 is itself a palindrome.
Input: N = 65
Output:
65 can be expressed as a sum of three palindromes (55, 9, 1).

Approach:
We can use Dynamic Programming to solve this problem. The idea is to first generate all the palindromes up to N in a sorted fashion, and then we can treat this problem as a variation of the subset sum problem, where we have to find the size of the smallest subset such that its sum is N.
Below is the implementation of above approach:

## CPP

 // C++ implementation of above approach#include using namespace std; // Declaring the DP table as global variablevector > dp;  // A utility for creating palindromeint createPalindrome(int input, bool isOdd){    int n = input;    int palin = input;     // checks if number of digits is odd or even    // if odd then neglect the last digit of input in    // finding reverse as in case of odd number of    // digits middle element occur once    if (isOdd)        n /= 10;     // Creates palindrome by just appending reverse    // of number to itself    while (n > 0) {        palin = palin * 10 + (n % 10);        n /= 10;    }     return palin;} // Function to generate palindromesvector generatePalindromes(int N){    vector palindromes;    int number;     // Run two times for odd and even length palindromes    for (int j = 0; j < 2; j++) {        // Creates palindrome numbers with first half as i.        // Value of j decides whether we need an odd length        // or even length palindrome.        int i = 1;        while ((number = createPalindrome(i++, j)) <= N)            palindromes.push_back(number);    }     return palindromes;} // Function to find the minimum// number of elements in a sorted// array A[i..j] such that their sum is Nlong long minimumSubsetSize(vector& A, int i, int j, int N){    if (!N)        return 0;     if (i > j || A[i] > N)        return INT_MAX;     if (dp[i][N])        return dp[i][N];     dp[i][N] = min(1 + minimumSubsetSize(A, i + 1, j,                                         N - A[i]),                   minimumSubsetSize(A, i + 1, j, N));     return dp[i][N];} // Function to find the minimum// number of palindromes that N// can be expressed as a sum ofint minimumNoOfPalindromes(int N){    // Getting the list of all palindromes upto N    vector palindromes = generatePalindromes(N);     // Sorting the list of palindromes    sort(palindromes.begin(), palindromes.end());     // Initializing the DP table    dp = vector >(palindromes.size(),                                    vector(N + 1, 0));     // Returning the required value    return minimumSubsetSize(palindromes, 0,                             palindromes.size() - 1, N);} // Driver codeint main(){    int N = 65;    cout << minimumNoOfPalindromes(N);    return 0;}

## Java

 /*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG {  // Java implementation of above approach   // Declaring the DP table as global variable  static long[][] dp;    // A utility for creating palindrome  static int createPalindrome(int input, int isOdd)  {    int n = input;    int palin = input;     // checks if number of digits is odd or even    // if odd then neglect the last digit of input in    // finding reverse as in case of odd number of    // digits middle element occur once    if (isOdd > 0)      n /= 10;     // Creates palindrome by just appending reverse    // of number to itself    while (n > 0) {      palin = palin * 10 + (n % 10);      n /= 10;    }     return palin;  }   // Function to generate palindromes  static ArrayList generatePalindromes(int N)  {    ArrayList palindromes = new ArrayList<>();    int number;     // Run two times for odd and even length palindromes    for (int j = 0; j < 2; j++) {      // Creates palindrome numbers with first half as i.      // Value of j decides whether we need an odd length      // or even length palindrome.      int i = 1;      while ((number = createPalindrome(i++, j)) <= N)        palindromes.add(number);    }     return palindromes;  }   // Function to find the minimum  // number of elements in a sorted  // array A[i..j] such that their sum is N  static long minimumSubsetSize(ArrayList A, int i, int j, int N)  {    if (N == 0)      return 0;     if (i > j || A.get(i) > N)      return Integer.MAX_VALUE;     if (dp[i][N] > 0)      return dp[i][N];     dp[i][N] = Math.min(1 + minimumSubsetSize(A, i + 1, j,                                              N - A.get(i)),                        minimumSubsetSize(A, i + 1, j, N));     return dp[i][N];  }   // Function to find the minimum  // number of palindromes that N  // can be expressed as a sum of  static int minimumNoOfPalindromes(int N)  {    // Getting the list of all palindromes upto N    ArrayList palindromes = generatePalindromes(N);     // Sorting the list of palindromes    Collections.sort(palindromes);     // Initializing the DP table    dp = new long [palindromes.size()][N + 1];       // Returning the required value    return (int)minimumSubsetSize(palindromes, 0,                                  palindromes.size() - 1, N);  }   // Driver Code  public static void main(String args[])  {    int N = 65;    System.out.println(minimumNoOfPalindromes(N));  }} // This code is contributed by shinjanpatra.

## Python3

 # Python3 implementation of above approach # Declaring the DP table as global variabledp = [[0 for i in range(1000)] for i in range(1000)] # A utility for creating palindromedef createPalindrome(input, isOdd):     n = input    palin = input     # checks if number of digits is odd or even    # if odd then neglect the last digit of input in    # finding reverse as in case of odd number of    # digits middle element occur once    if (isOdd):        n //= 10     # Creates palindrome by just appending reverse    # of number to itself    while (n > 0):        palin = palin * 10 + (n % 10)        n //= 10     return palin # Function to generate palindromesdef generatePalindromes(N):     palindromes = []    number = 0     # Run two times for odd and even length palindromes    for j in range(2):                 # Creates palindrome numbers with first half as i.        # Value of j decides whether we need an odd length        # or even length palindrome.        i = 1        number = createPalindrome(i, j)        while number <= N:            number = createPalindrome(i, j)            palindromes.append(number)            i += 1     return palindromes # Function to find the minimum# number of elements in a sorted# array A[i..j] such that their sum is Ndef minimumSubsetSize(A, i, j, N):     if (not N):        return 0     if (i > j or A[i] > N):        return 10**9     if (dp[i][N]):        return dp[i][N]     dp[i][N] = min(1 + minimumSubsetSize(A, i + 1, j, N - A[i]),                    minimumSubsetSize(A, i + 1, j, N))     return dp[i][N] # Function to find the minimum# number of palindromes that N# can be expressed as a sum ofdef minimumNoOfPalindromes(N):     # Getting the list of all palindromes upto N    palindromes = generatePalindromes(N)     # Sorting the list of palindromes    palindromes = sorted(palindromes)     # Returning the required value    return minimumSubsetSize(palindromes, 0, len(palindromes) - 1, N) # Driver codeN = 65print(minimumNoOfPalindromes(N)) # This code is contributed by mohit kumar 29

## C#

 // C# program to implement the approachusing System;using System.Collections.Generic; class GFG {   // Declaring the DP table as global variable  static long[, ] dp;   // A utility for creating palindrome  static int createPalindrome(int input, int isOdd)  {    int n = input;    int palin = input;     // checks if number of digits is odd or even    // if odd then neglect the last digit of input in    // finding reverse as in case of odd number of    // digits middle element occur once    if (isOdd > 0)      n /= 10;     // Creates palindrome by just appending reverse    // of number to itself    while (n > 0) {      palin = palin * 10 + (n % 10);      n /= 10;    }     return palin;  }   // Function to generate palindromes  static List generatePalindromes(int N)  {    List palindromes = new List();    int number;     // Run two times for odd and even length palindromes    for (int j = 0; j < 2; j++) {      // Creates palindrome numbers with first half as      // i. Value of j decides whether we need an odd      // length or even length palindrome.      int i = 1;      while ((number = createPalindrome(i++, j)) <= N)        palindromes.Add(number);    }     return palindromes;  }   // Function to find the minimum  // number of elements in a sorted  // array A[i..j] such that their sum is N  static long minimumSubsetSize(List A, int i, int j,                                int N)  {    if (N == 0)      return 0;     if (i > j || A[i] > N)      return Int32.MaxValue;     if (dp[i, N] > 0)      return dp[i, N];     dp[i, N] = Math.Min(      1 + minimumSubsetSize(A, i + 1, j, N - A[i]),      minimumSubsetSize(A, i + 1, j, N));     return dp[i, N];  }   // Function to find the minimum  // number of palindromes that N  // can be expressed as a sum of  static int minimumNoOfPalindromes(int N)  {    // Getting the list of all palindromes upto N    List palindromes = generatePalindromes(N);     // Sorting the list of palindromes    palindromes.Sort();     // Initializing the DP table    dp = new long[palindromes.Count, N + 1];     // Returning the required value    return (int)minimumSubsetSize(      palindromes, 0, palindromes.Count - 1, N);  }   // Driver Code  public static void Main(string[] args)  {    int N = 65;    Console.WriteLine(minimumNoOfPalindromes(N));  }} // This code is contributed by phasing17.

## Javascript



Output:

3

My Personal Notes arrow_drop_up