Smallest N digit number whose sum of square of digits is a Perfect Square | function to check if number is a perfect square ; Function to calculate the smallest N digit number ; Place digits greater than equal to prev ; Check if placing this digit leads to a solution then return it ; Else backtrack ; Create a string representing the N digit number ; Initialise N
function isSquare ( n ) { let k = Math . floor ( Math . sqrt ( n ) ) ; return k * k == n ? 1 : 0 ; } function calculate ( pos , prev , sum , v ) { if ( pos == v . length ) return isSquare ( sum ) ; for ( let i = prev ; i <= 9 ; i ++ ) { v [ pos ] = i ; sum += i * i ; if ( calculate ( pos + 1 , i , sum , v ) != 0 ) return 1 ; sum -= ( i * i ) ; } return 0 ; } function minValue ( n ) { let v = Array . from ( { length : n } , ( _ , i ) => 0 ) ; if ( calculate ( 0 , 1 , 0 , v ) != 0 ) { let answer = " " ; for ( let i = 0 ; i < v . length ; i ++ ) answer += ( v [ i ] + 0 ) ; return answer ; } else return " " ; } let N = 2 ; document . write ( minValue ( N ) ) ;