If MSD is 4. For example if n = 428 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 399 2 ) Count of numbers from 400 to 428 which is 29.
if ( $ msd == 4 ) return ( $ msd ) * $ a [ $ d ] + ( $ n % $ p ) + 1 ;