Find Nth positive number whose digital root is X | Function to find the digital root of a number ; Function to find the Nth number with digital root as X ; Counter variable to keep the count of valid numbers ; Find digital root ; Check if is required answer or not ; Print the answer if you have found it and breakout of the loop ; Driver Code
function findDigitalRoot ( num ) { var sum = Number . MAX_VALUE , tempNum = num ; while ( sum >= 10 ) { sum = 0 ; while ( tempNum > 0 ) { sum += tempNum % 10 ; tempNum = parseInt ( tempNum / 10 ) ; } tempNum = sum ; } return sum ; } function findAnswer ( X , N ) { var counter = 0 ; for ( var i = 1 ; counter < N ; ++ i ) { var digitalRoot = findDigitalRoot ( i ) ; if ( digitalRoot == X ) { counter += 1 ; } if ( counter == N ) { document . write ( i ) ; break ; } } } var X = 1 , N = 3 ; findAnswer ( X , N ) ;