Given a string S, the task is to print all words with prime length in the given string.
Examples:
Input: S = “This is a python programming language”
Output: is
programming
Explanation: Length of is is 2 and length of programming is 11 both are primes
Input: S = “You are using geeksforgeeks”
Output: You
are
using
geeksforgeeks
Approach 1:
To solve the problem follow the below steps:
- First split the given string to get an array of space-separated strings.
- Start traversing the words from left to right.
- Calculate the length of each word.
- If the length is prime, then print the word.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int x)
{
int prime = 0;
if (x == 2)
return 1;
if (x > 1) {
for ( int i = 2; i < sqrt (x) + 1; i++) {
if (x % i == 0) {
prime = 1;
break ;
}
}
if (prime == 0)
return true ;
else
return false ;
}
else
return false ;
}
void printPrimeLenWords(string& s)
{
s += ' ' ;
string temp;
for ( int i = 0; i < s.length(); i++) {
if (s[i] == ' ' ) {
if (isPrime(temp.size())) {
cout << temp << "\n" ;
}
temp = "" ;
}
else
temp += s[i];
}
}
int main()
{
string s = "This is a python programming language" ;
printPrimeLenWords(s);
return 0;
}
|
Java
import java.io.*;
class GFG {
public static boolean isPrime( int x)
{
int prime = 0 ;
if (x == 2 )
return true ;
if (x > 1 ) {
for ( int i = 2 ; i < Math.sqrt(x) + 1 ; i++) {
if (x % i == 0 ) {
prime = 1 ;
break ;
}
}
if (prime == 0 )
return true ;
else
return false ;
}
else
return false ;
}
public static void printPrimeLenWords(String s)
{
s += " " ;
String temp = "" ;
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) == ' ' ) {
if (isPrime(temp.length())) {
System.out.println(temp);
}
temp = "" ;
}
else
temp += s.charAt(i);
}
}
public static void main(String[] args)
{
String s = "This is a python programming language" ;
printPrimeLenWords(s);
}
}
|
Python3
from math import sqrt
def isPrime(x):
prime = 0
if (x > 1 ):
for i in range ( 2 , int (sqrt(x)) + 1 ):
if (x % i = = 0 ):
prime = 1
break
if (prime = = 0 ):
return True
else :
return False
else :
return False
def printPrimeLenWords(s):
s = s.split()
for i in s:
if isPrime( len (i)):
print (i)
if __name__ = = '__main__' :
st = "This is a python programming language"
printPrimeLenWords(st)
|
C#
using System;
public class GFG {
public static bool isPrime( int x)
{
int prime = 0;
if (x == 2)
return true ;
if (x > 1) {
for ( int i = 2; i < Math.Sqrt(x) + 1; i++) {
if (x % i == 0) {
prime = 1;
break ;
}
}
if (prime == 0)
return true ;
else
return false ;
}
else
return false ;
}
public static void printPrimeLenWords( string s)
{
s += ' ' ;
string temp = "" ;
for ( int i = 0; i < s.Length; i++) {
if (s[i] == ' ' ) {
if (isPrime(temp.Length)) {
Console.WriteLine(temp);
}
temp = "" ;
}
else
temp += s[i];
}
}
static public void Main()
{
string s = "This is a python programming language" ;
printPrimeLenWords(s);
}
}
|
Javascript
function isPrime(x)
{
prime = 0
if (x == 2) return 1
if (x > 1) {
for (let i = 2; i < Math.sqrt(x) + 1; i++) {
if (x % i == 0) {
prime = 1
break
}
}
if (prime == 0)
return true
else
return false
}
else
return false
}
function printPrimeLenWords(s) {
s = s.split( ' ' )
for (let i = 0; i < s.length; i++)
if (isPrime(s[i].length))
console.log(s[i])
}
st = "This is a python programming language"
printPrimeLenWords(st)
|
Time complexity: O(n * sqrt(x)), where n is the number of words in the given sentence and x be the length of the largest string.
Auxiliary Space: O(1)
Approach 2:
Step 1: Initially store all the prime number uptill the pow(10, 5) using the Sieve of Eratosthenes into a set data structure.
Step 2: Run the for loop for every word and search the length of that word into the set.
Step 3: If word length is present then print else continue.
Implementation for the above approach : –
C++
#include<bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes( int n, set< int > &store)
{
bool prime[n+1];
memset (prime, true , sizeof (prime));
for ( int p=2; p*p<=n; p++)
{
if (prime[p] == true )
{
for ( int i=p*2; i<=n; i += p)
prime[i] = false ;
}
}
for ( int p=2; p<=n; p++)
if (prime[p])
store.insert(p);
}
int main(){
set< int > store;
string s = "This is a python programming language" ;
SieveOfEratosthenes(s.size(), store);
istringstream iss(s);
string word;
while (iss >> word){
if (store.find(word.size()) != store.end()){
cout << word << endl;
}
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static Set<Integer> store = new HashSet<>();
static void SieveOfEratosthenes( int n)
{
boolean [] prime = new boolean [n + 1 ];
Arrays.fill(prime, true );
for ( int p = 2 ; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * 2 ; i <= n; i += p) {
prime[i] = false ;
}
}
}
for ( int p = 2 ; p <= n; p++) {
if (prime[p]) {
store.add(p);
}
}
}
public static void main(String[] args)
{
String s = "This is a python programming language" ;
SieveOfEratosthenes(s.length());
String[] words = s.split( " " );
for (String word : words) {
if (store.contains(word.length())) {
System.out.println(word);
}
}
}
}
|
Python3
def SieveOfEratosthenes( n, store):
prime = [ 1 ] * (n + 1 );
p = 2 ;
while (p * p< = n):
if (prime[p] = = True ):
for i in range ( 2 * p, n + 1 , p):
prime[i] = False ;
p + = 1 ;
for p in range ( 2 ,n + 1 , 1 ):
if (prime[p]):
store.add(p);
store = set ();
s = "This is a python programming language" ;
SieveOfEratosthenes( len (s), store);
words = s.split();
for i in range ( 0 , len (words)):
word = words[i];
if ( len (word) in store):
print (word);
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static HashSet< int > store = new HashSet< int >();
static void SieveOfEratosthenes( int n)
{
bool [] prime = new bool [n + 1];
for ( int i = 0; i <= n; i++) {
prime[i] = true ;
}
for ( int p = 2; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * 2; i <= n; i += p) {
prime[i] = false ;
}
}
}
for ( int p = 2; p <= n; p++) {
if (prime[p]) {
store.Add(p);
}
}
}
static public void Main()
{
string s = "This is a python programming language" ;
SieveOfEratosthenes(s.Length);
string [] words = s.Split( " " );
foreach ( string word in words)
{
if (store.Contains(word.Length)) {
Console.WriteLine(word);
}
}
}
}
|
Javascript
function SieveOfEratosthenes(n, store) {
let prime = Array(n + 1).fill( true );
for (let p = 2; p * p <= n; p++) {
if (prime[p] === true ) {
for (let i = p * 2; i <= n; i += p) {
prime[i] = false ;
}
}
}
for (let p = 2; p <= n; p++) {
if (prime[p]) {
store.add(p);
}
}
}
let store = new Set();
let s = 'This is a python programming language' ;
SieveOfEratosthenes(s.length, store);
let words = s.split( ' ' );
for (let word of words) {
if (store.has(word.length)) {
document.write(word);
document.write( "<br>" );
}
}
|
Time complexity: O(n*log(logn)), where n = size of string
Auxiliary Space: O(n)
Approach 3:
Step 1: Iterate over the characters of the string one by one.
Step 2: Whenever we encounter a space character, we check if the length of the word is prime or not.
Step 3: If it is, we print the word. We also check same for the last word which is not followed by a space character.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int p)
{
if (p <= 1)
return false ;
else if (p == 2 || p == 3)
return true ;
else if (p % 2 == 0 || p % 3 == 0)
return false ;
else {
for ( int i = 5; i * i <= p; i += 6) {
if (p % i == 0 || p % (i + 2) == 0)
return false ;
}
}
return true ;
}
int main()
{
string s = "This is a python programming language" ;
string word;
for ( int i = 0; i < s.length(); i++) {
if (s[i] != ' ' ) {
word += s[i];
}
else {
if (isPrime(word.length())) {
cout << word << endl;
}
word.clear();
}
}
if (isPrime(word.length())) {
cout << word << endl;
}
return 0;
}
|
Java
import java.util.*;
public class Main {
static boolean isPrime( int p)
{
if (p <= 1 )
return false ;
else if (p == 2 || p == 3 )
return true ;
else if (p % 2 == 0 || p % 3 == 0 )
return false ;
else {
for ( int i = 5 ; i * i <= p; i += 6 ) {
if (p % i == 0 || p % (i + 2 ) == 0 )
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
String s = "This is a python programming language" ;
String word = "" ;
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) != ' ' ) {
word += s.charAt(i);
}
else {
if (isPrime(word.length())) {
System.out.println(word);
}
word = "" ;
}
}
if (isPrime(word.length())) {
System.out.println(word);
}
}
}
|
Python3
import math
def isPrime(p):
if p < = 1 :
return False
elif p = = 2 or p = = 3 :
return True
elif p % 2 = = 0 or p % 3 = = 0 :
return False
else :
for i in range ( 5 , int (math.sqrt(p)) + 1 , 6 ):
if p % i = = 0 or p % (i + 2 ) = = 0 :
return False
return True
s = "This is a python programming language"
word = ""
for i in range ( len (s)):
if s[i] ! = " " :
word + = s[i]
else :
if isPrime( len (word)):
print (word)
word = ""
if isPrime( len (word)):
print (word)
|
C#
using System;
class Gfg{
static bool isPrime( int p)
{
if (p <= 1)
return false ;
else if (p == 2 || p == 3)
return true ;
else if (p % 2 == 0 || p % 3 == 0)
return false ;
else {
for ( int i = 5; i * i <= p; i += 6) {
if (p % i == 0 || p % (i + 2) == 0)
return false ;
}
}
return true ;
}
public static void Main()
{
string s = "This is a python programming language" ;
string word= "" ;
for ( int i = 0; i < s.Length; i++) {
if (s[i] != ' ' ) {
word += s[i];
}
else {
if (isPrime(word.Length)) {
Console.WriteLine(word);
}
word= "" ;
}
}
if (isPrime(word.Length)) {
Console.WriteLine(word);
}
}
}
|
Javascript
function isPrime(p) {
if (p <= 1)
return false ;
else if (p == 2 || p == 3)
return true ;
else if (p % 2 == 0 || p % 3 == 0)
return false ;
else {
for (let i = 5; i * i <= p; i += 6) {
if (p % i == 0 || p % (i + 2) == 0)
return false ;
}
}
return true ;
}
let s = "This is a python programming language" ;
let word = "" ;
for (let i = 0; i < s.length; i++) {
if (s[i] != " " ) {
word += s[i];
} else {
if (isPrime(word.length)) {
console.log(word);
}
word = "" ;
}
}
if (isPrime(word.length)) {
console.log(word);
}
|
Time complexity: O(N*sqrt(N)), where N is the length of the string.
Auxiliary Space: O(K), where K is the length of the biggest word in the string.
Approach 4:
Step 1: First split the sentence into words using repeted iteration of getline() function.
Step 2: In each iteartion, we check if the length of the word is prime or not using Wilson Primality Test.
Step 3: If it is prime, then we print the word.
C++
#include <bits/stdc++.h>
using namespace std;
long long fact( const int & p)
{
if (p <= 1)
return 1;
return p * fact(p - 1);
}
bool isPrime( const long long & p)
{
if (p == 4 || p <= 1)
return false ;
long long a = fact(p - 1) % p;
if (a == p - 1)
return true ;
return false ;
}
int main()
{
string s = "This is a python programming language" ;
string word;
istringstream iss(s);
while (getline(iss, word, ' ' )) {
if (isPrime(word.length()))
cout << word << endl;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
public static long fact( final int p) {
if (p <= 1 ) {
return 1 ;
}
return p * fact(p - 1 );
}
public static boolean isPrime( final long p) {
if (p == 4 || p <= 1 ) {
return false ;
}
final long a = fact(( int ) (p - 1 )) % p;
if (a == p - 1 ) {
return true ;
}
return false ;
}
public static void main( final String[] args) {
final String s = "This is a python programming language" ;
String word;
final Scanner iss = new Scanner(s);
iss.useDelimiter( " " );
while (iss.hasNext()) {
word = iss.next();
if (isPrime(word.length())) {
System.out.println(word);
}
}
iss.close();
}
}
|
Python3
def fact(p):
if p < = 1 :
return 1
return p * fact(p - 1 )
def isPrime(p):
if p = = 4 or p < = 1 :
return False
a = fact(p - 1 ) % p
if a = = p - 1 :
return True
return False
s = "This is a python programming language"
words = s.split( ' ' )
for word in words:
if isPrime( len (word)):
print (word)
|
Time complexity: O(N*K), where N is the length of the sentence and K is the length of the biggest word in the string.
Auxiliary Space: O(K)
Please Login to comment...