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 ] - '0' ] == 0 && prevprime [ N [ j ] - '0' ] == 0 ) { ans [ j ] = N [ j ] = '7' ; N [ j - 1 ] = prevprime [ N [ j - 1 ] - '0' ] + '0' ; ans [ j - 1 ] = N [ j - 1 ] ; small = 1 ; j -- ; } i = ns ; } } }