Open In App

C++ Program to Print the Largest Possible Prime Number From a Given Number

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to Print the Largest
// Possible Prime Number From a
// Given Number
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// function to check whether the
// substring is prime or not
bool isprime(string f)
{
    int n = stoi(f);
   
    // corner case check
    if (n <= 1)
        return false;
 
    // Check from 2 to n-1
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
int longp(int a)
{
    // convert the number to a string
    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++) {
           
            // calculate the substrings of the string
            string p = d.substr(i, len);
           
            // pass the substring to the prime check
            // function
            if (isprime(p)) {
                int l = stoi(p);
               
                // store the maximum value of the prime
                // substring
                c = max(c, l);
            }
        }
    }
    return c;
}
// Driver Code
int main()
{
 
    long long int n = 12691;
    int k = longp(n);
    cout << k;
    return 0;
}


Output

691

Time Complexity: O(N3)
Auxiliary Space: O(1)



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads