
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest Number with Prime Digits in C++
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.
- If the current digit is not prime.
- Return n.
Example
Let's see the code.
#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.