C++ Program to Print the Largest Possible Prime Number From a Given Number
Given an integer, the task is to find the largest prime number that can be made out of that. If we consider the integer as a string of digits, then the prime number can be a substring of any length. The examples given below will clarify the idea of the problem.
Example:
Input: 12691
Output: 691
Approach:
- Create a string of the given number
- Compute all the substrings of the string
- Check whether any substring is prime or not
- If a substring is prime, maximize its value by comparing it with the other prime substrings
- Return the maximum value of the prime substring
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bool isprime(string f)
{
int n = stoi(f);
if (n <= 1)
return false ;
for ( int i = 2; i < n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
int longp( int a)
{
string d = to_string(a);
int n = d.length();
int c = INT_MIN;
for ( int i = 0; i < n; i++) {
for ( int len = 1; len <= n - i; len++) {
string p = d.substr(i, len);
if (isprime(p)) {
int l = stoi(p);
c = max(c, l);
}
}
}
return c;
}
int main()
{
long long int n = 12691;
int k = longp(n);
cout << k;
return 0;
}
|
Time Complexity: O(N3)
Auxiliary Space: O(1)
Last Updated :
07 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...