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
< ? php function findDigitalRoot ( $ num ) { $ sum = PHP_INT_MAX ; $ tempNum = $ num ; while ( $ sum >= 10 ) { $ sum = 0 ; while ( $ tempNum > 0 ) { $ sum += $ tempNum % 10 ; $ tempNum /= 10 ; } $ tempNum = $ sum ; } return $ sum ; } function findAnswer ( $ X , $ N ) { $ counter = 0 ; for ( $ i = 1 ; $ counter < $ N ; ++ $ i ) { $ digitalRoot = findDigitalRoot ( $ i ) ; if ( $ digitalRoot == $ X ) { ++ $ counter ; } if ( $ counter == $ N ) { echo ( $ i ) ; break ; } } } $ X = 1 ; $ N = 3 ; findAnswer ( $ X , $ N ) ;