Largest number with prime digits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the largest number with prime digits that is less than n.

Let's see the steps to solve the problem.

  • Write a loop that iterates from 0 to n.
    • If the current digit is not prime.
      • While the digit is less 2, decrement the i value. If the i value is negative, then make it 0.
      • Update the current index value with the next smallest prime digit.
      • From the next index, make every digit to 7.
  • Return n.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isPrime(char c) {
   return c == '2' || c == '3' || c == '5' || c == '7';
}
void decrease(string& n, int i) {
   if (n[i] <= '2') {
      n.erase(i, 1);
      n[i] = '7';
   }else if (n[i] == '3') {
      n[i] = '2';
   }else if (n[i] <= '5') {
      n[i] = '3';
   }else if (n[i] <= '7') {
      n[i] = '5';
   }else {
      n[i] = '7';
   }
   return;
}
string getPrimeDigitsNumber(string n) {
   for (int i = 0; i < n.length(); i++) {
      if (!isPrime(n[i])) {
         while (n[i] <= '2' && i >= 0) {
            i--;
         }
         if (i < 0) {
            i = 0;
         }
         decrease(n, i);
         for (int j = i + 1; j < n.length(); j++) {
            n[j] = '7';
         }
         break;
      }
   }
   return n;
}
int main() {
   string n = "7464";
   cout << getPrimeDigitsNumber(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

7377

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 09-Apr-2021 13:44:43
Advertisements