Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 01 Aug, 2022
View Discussion
Improve Article
Save Article

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.

Input: 

12691

Output: 

691

Explanation: The three numbers in the number 12691 are 269,691. The greater number is 691 and hence we print this.

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!