Minimum number of palindromes required to express N as a sum | Set 2 | A utility for creating palindrome ; 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 ; Creates palindrome by just appending reverse of number to itself ; Function to generate palindromes ; Run two times for odd and even length palindromes ; Creates palindrome numbers with first half as i . Value of j decides whether we need an odd length or even length palindrome . ; Swap values of left and right ; Function to find the minimum number of palindromes required to express N as a sum ; Checking if the number is a palindrome ; Checking if the number is a sum of two palindromes Getting the list of all palindromes upto N ; Sorting the list of palindromes ; The answer is three if the control reaches till this point ; Driver code
function createPalindrome ( input , isOdd ) { var n = input ; var palin = input ; if ( isOdd % 2 == 1 ) { n = parseInt ( n / 10 ) ; } while ( n > 0 ) { palin = palin * 10 + ( n % 10 ) ; n = parseInt ( n / 10 ) ; } return palin ; } function generatePalindromes ( N ) { var palindromes = [ ] ; var number ; for ( var j = 0 ; j < 2 ; j ++ ) { var i = 1 ; while ( ( number = createPalindrome ( i ++ , j ) ) <= N ) { palindromes . push ( number ) ; } } return palindromes ; } function reverse ( input ) { var temparray = input . split ( ' ' ) ; var left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { var temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return temparray . join ( ' ' ) ; } function minimumNoOfPalindromes ( N ) { var a = N . toString ( ) ; var b = N . toString ( ) ; b = reverse ( b ) ; if ( a == b ) { return 1 ; } var palindromes = generatePalindromes ( N ) ; palindromes . sort ( ) ; var l = 0 , r = palindromes . length - 1 ; while ( l < r ) { if ( palindromes [ l ] + palindromes [ r ] == N ) { return 2 ; } else if ( palindromes [ l ] + palindromes [ r ] < N ) { ++ l ; } else { -- r ; } } return 3 ; } var N = 65 ; document . write ( minimumNoOfPalindromes ( N ) ) ;