Largest number with prime digits | CPP program to find largest number smaller than equal to n with all prime digits . ; check if character is prime ; replace with previous prime character ; if 2 erase s [ i ] and replace next with 7 ; find first non prime char ; find first char greater than 2 ; like 20 ; like 7721 ; replace remaining with 7 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( char c ) { return ( c == '2' c == '3' c == '5' c == '7' ) ; } void decrease ( string & s , int i ) { if ( s [ i ] <= '2' ) { s . erase ( i , 1 ) ; s [ i ] = '7' ; } else if ( s [ i ] == '3' ) s [ i ] = '2' ; else if ( s [ i ] <= '5' ) s [ i ] = '3' ; else if ( s [ i ] <= '7' ) s [ i ] = '5' ; else s [ i ] = '7' ; return ; } string primeDigits ( string s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! isPrime ( s [ i ] ) ) { while ( s [ i ] <= '2' && i >= 0 ) i -- ; if ( i < 0 ) { i = 0 ; decrease ( s , i ) ; } else decrease ( s , i ) ; for ( int j = i + 1 ; j < s . length ( ) ; j ++ ) s [ j ] = '7' ; break ; } } return s ; } int main ( ) { string s = "45" ; cout << primeDigits ( s ) << endl ; s = "1000" ; cout << primeDigits ( s ) << endl ; s = "7721" ; cout << primeDigits ( s ) << endl ; s = "7221" ; cout << primeDigits ( s ) << endl ; s = "74545678912345689748593275897894708927680" ; cout << primeDigits ( s ) << endl ; return 0 ; }