Make current digit as 7 Go left of the digit and make it largest prime less than number . Continue do that until we found a digit which has some largest prime less than it
while ( j > 0 && p [ N [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 && prevprime [ N [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 ) { ans [ j ] = N [ j ] = ' ' ; N [ j - 1 ] = String . fromCharCode ( prevprime [ N [ j - 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] + ' ' . charCodeAt ( 0 ) ) ; ans [ j - 1 ] = N [ j - 1 ] ; small = 1 ; j -- ; } i = ns ; } } }