• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
November 10, 2022 |540 Views
C++ Program to Print the Largest possible Prime Number from a given number
  Share  1 Like
Description
Discussion

In this video, we will write a program to print largest possible prime number from a given number. Here, If we consider the integer as a string of digits, then the prime number can be a substring of any length.

Example:

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

Here we see two different methods for printing the largest possible prime number from a given number.

Simple Approach 1:
Step 1: Create a string of the given number
Step 2: Find all the substrings of the above-made string.
Step 3: Convert substring to number.
Step 4: Check whether any substring is prime or not
Step 5: If a substring is prime, maximize its value by comparing it with the other prime substrings
Step 6: Print maximum value prime substring.


Optimum Approach 2:
Step 1: Create a string of the given number
Step 2: Find all the substrings of the above-made string.
Step 3: Convert substring to number.
Step 4: Check whether any substring is prime or not
Step 5: If a substring is prime, maximize its value by comparing it with the other prime substrings
Step 6: Print maximum value prime substring.

Note: The difference in this approach is a difference in function checking whether a number is prime or not.

Let us assume the length of the string converted from number = l.

So the time and space complexity are: 

  • Approach 1 is O(l^2*n) and O(l)
  • Approach 2 is O(l^2*sqrt(n)) and O(l)

C++ program to print the largest possible prime number from a given number:
https://www.geeksforgeeks.org/cpp-program-to-print-the-largest-possible-prime-number-from-a-given-number/

Read More