Given a Binary string, the task is to find the largest Prime Number possible by the decimal representation of a subsequence of the given binary string. If no prime number can be obtained, print -1.
Examples:
Input: S = “1001”
Output: 5
Explanation: Out of all subsequences of the string “1001”, the largest prime number that can be obtained is “101” (= 5).
Input: “1011”
Output: 11
Explanation: Out of all subsequences of the string “1011”, the largest prime number that can be obtained is “1011” (= 11).
Approach: To solve the problem, the idea is to generate all possible subsequences of the string, and convert each subsequence to its equivalent decimal form. Print the largest prime number obtained from this subsequences.
Follow the steps below to solve this problem:
- Initialize a vector of pairs, say vec, for storing pairs of strings and their equivalent decimal values, in Pair.first and Pair.second respectively.
- Initialize a variable, say ans, to store the required answer.
- Iterate a loop from i = 0 to length of the string s:
- Iterate a loop from j = 0 to the length of vec:
- Store the jth pair in temp.
- If the ith character of string s is ‘1‘:
- Add the character in temp.first.
- Update the value of temp.second by left shifting the current value and adding 1 to it.
- Otherwise:
- Add the character in temp.first.
- Update the value of temp.second by left shifting the current value and adding 0 to it.
- Store this temp pair into vec.
- If the temp.second is prime:
- Store max of ans and temp.second in ans.
- If ans is equal to 0:
- No prime number can be obtained from the string s.
- Otherwise:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
bool isPrime( int x)
{
if (x <= 1)
return false ;
for ( int i = 2; i * i <= x; i++) {
if (x % i == 0)
return false ;
}
return true ;
}
void largestPrime(string s)
{
vector<pair<string, int > > vec{ { "" , 0 } };
int ans = 0;
for ( int i = 0; i < s.length(); i++) {
int n = vec.size();
for ( int j = 0; j < n; j++) {
pair<string, int > temp = vec[j];
string str = temp.first;
int val = temp.second;
if (s[i] == '1' ) {
temp.first = str + '1' ;
temp.second = ((val << 1) + 1);
}
else {
temp.first = str + '0' ;
temp.second = ((val << 1) + 0);
}
vec.push_back(temp);
int check = temp.second;
if (isPrime(check)) {
ans = max(ans, check);
}
}
}
if (ans == 0)
cout << -1 << endl;
else
cout << ans << endl;
}
int main()
{
string s = "110" ;
largestPrime(s);
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean isPrime( int x)
{
if (x <= 1 )
return false ;
for ( int i = 2 ; i * i <= x; i++) {
if (x % i == 0 )
return false ;
}
return true ;
}
static void largestPrime(String s)
{
List<StringIntPair> vec = new ArrayList<>();
vec.add( new StringIntPair( "" , 0 ));
int ans = 0 ;
for ( int i = 0 ; i < s.length(); i++) {
int n = vec.size();
for ( int j = 0 ; j < n; j++) {
StringIntPair ele = vec.get(j);
String str = ele.str;
int val = ele.val;
if (s.charAt(i) == '1' ) {
str = str + '1' ;
val = ((val << 1 ) + 1 );
}
else {
str = str + '0' ;
val = ((val << 1 ) + 0 );
}
vec.add( new StringIntPair(str, val));
int check = val;
if (isPrime(check)) {
ans = Math.max(ans, check);
}
}
}
if (ans == 0 )
System.out.println(- 1 );
else
System.out.println(ans);
}
public static void main(String[] args)
{
String s = "110" ;
largestPrime(s);
}
static class StringIntPair {
String str;
int val;
StringIntPair(String str, int val)
{
this .str = str;
this .val = val;
}
}
}
|
Python3
def isPrime(x):
if (x < = 1 ):
return False
for i in range ( 2 , x + 1 ):
if i * i > x:
break
if (x % i = = 0 ):
return False
return True
def largestPrime(s):
vec = [["", 0 ]]
ans = 0
for i in range ( len (s)):
n = len (vec)
for j in range (n):
temp = vec[j]
str = temp[ 0 ]
val = temp[ 1 ]
if (s[i] = = '1' ):
temp[ 0 ] = str + '1'
temp[ 1 ] = ((val << 1 ) + 1 )
else :
temp[ 0 ] = str + '0'
temp[ 1 ] = ((val << 1 ) + 0 )
vec.append(temp)
check = temp[ 1 ]
if (isPrime(check)):
ans = max (ans, check)
break
if (ans = = 0 ):
print ( - 1 )
else :
print (ans)
if __name__ = = '__main__' :
s = "110"
largestPrime(s)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool IsPrime( int x)
{
if (x <= 1)
return false ;
for ( int i = 2; i * i <= x; i++) {
if (x % i == 0)
return false ;
}
return true ;
}
static void LargestPrime( string s)
{
List<Tuple< string , int > > vec
= new List<Tuple< string , int > >();
vec.Add(Tuple.Create( "" , 0));
int ans = 0;
for ( int i = 0; i < s.Length; i++) {
int n = vec.Count;
for ( int j = 0; j < n; j++) {
var ele = vec[j];
string str = ele.Item1;
int val = ele.Item2;
if (s[i] == '1' ) {
str = str + '1' ;
val = ((val << 1) + 1);
}
else {
str = str + '0' ;
val = ((val << 1) + 0);
}
vec.Add(Tuple.Create(str, val));
int check = val;
if (IsPrime(check)) {
ans = Math.Max(ans, check);
}
}
}
if (ans == 0)
Console.WriteLine(-1);
else
Console.WriteLine(ans);
}
public static void Main( string [] args)
{
string s = "110" ;
LargestPrime(s);
}
}
|
Javascript
<script>
function isPrime(x) {
if (x <= 1)
return false ;
for (let i = 2; i * i <= x; i++) {
if (i * i > x){
break
}
if (x % i == 0)
return false ;
}
return true ;
}
function largestPrime(s) {
let vec = [[ "" , 0]];
let ans = 0;
for (let i = 0; i < s.length; i++) {
let n = vec.length;
for (let j = 0; j < n; j++) {
let temp = vec[j];
let str = temp[0];
let val = temp[1];
if (s[i] == '1' ) {
temp[0] = str + '1' ;
temp[1] = ((val << 1) + 1);
}
else {
temp[0] = str + '0' ;
temp[1] = ((val << 1) + 0);
}
vec.push(temp);
let check = temp[1];
if (isPrime(check)) {
ans = Math.max(ans, check);
break
}
}
}
if (ans == 0)
document.write(-1 + "<br>" );
else
document.write(ans + "<br>" );
}
let s = "110" ;
largestPrime(s);
</script>
|
Time Complexity: O(2N * ?N), where N is the length of the string.
Auxiliary Space: O(2N * N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
01 Feb, 2023
Like Article
Save Article