Print Words with Prime length from a Sentence
Last Updated :
29 Aug, 2023
+
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 repeated iteration of getline() function.
Step 2: In each iteration, 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)
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class Program {
static long Fact( int p)
{
if (p <= 1)
return 1;
return p * Fact(p - 1);
}
static bool IsPrime( long p)
{
if (p == 4 || p <= 1)
return false ;
long a = Fact(( int )(p - 1)) % p;
if (a == p - 1)
return true ;
return false ;
}
static void Main( string [] args)
{
string s = "This is a python programming language" ;
string [] words = s.Split( " " );
foreach ( string word in words)
{
if (IsPrime(word.Length)) {
Console.WriteLine(word);
}
}
}
}
|
Javascript
function fact(p) {
if (p <= 1) {
return 1;
}
return p * fact(p - 1);
}
function isPrime(p) {
if (p == 4 || p <= 1) {
return false ;
}
let a = fact(p - 1) % p;
if (a == p - 1) {
return true ;
}
return false ;
}
let s = "This is a python programming language" ;
let words = s.split( ' ' );
for (let i = 0; i < words.length; i++) {
if (isPrime(words[i].length)) {
console.log(words[i]);
}
}
|
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)
Approach 5:
Step 1: First split the sentence into words using repeated iteration of getline() function.
Step 2: In each iteration, we check if the length of the word is prime or not using Fermat Method.
Step 3: If it is prime, then we print the word.
C++
#include <bits/stdc++.h>
using namespace std;
int power( int a, unsigned int n, int p)
{
int res = 1;
a = a % p;
while (n > 0) {
if (n & 1)
res = (res * a) % p;
n = n >> 1;
a = (a * a) % p;
}
return res;
}
int gcd( int a, int b)
{
if (a < b)
return gcd(b, a);
else if (a % b == 0)
return b;
else
return gcd(b, a % b);
}
bool isPrime(unsigned int n)
{
int k = 3;
if (n <= 1 || n == 4)
return false ;
if (n <= 3)
return true ;
while (k > 0) {
int a = 2 + rand () % (n - 4);
if (gcd(n, a) != 1)
return false ;
if (power(a, n - 1, n) != 1)
return false ;
k--;
}
return true ;
}
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.util.Random;
public class GFG {
static int power( int a, int n, int p)
{
int res = 1 ;
a = a % p;
while (n > 0 ) {
if ((n & 1 ) != 0 )
res = (res * a) % p;
n = n >> 1 ;
a = (a * a) % p;
}
return res;
}
static int gcd( int a, int b)
{
if (a < b)
return gcd(b, a);
else if (a % b == 0 )
return b;
else
return gcd(b, a % b);
}
static boolean isPrime( int n)
{
int k = 3 ;
if (n <= 1 || n == 4 )
return false ;
if (n <= 3 )
return true ;
while (k > 0 ) {
Random rand = new Random();
int a = 2 + rand.nextInt(n - 4 );
if (gcd(n, a) != 1 )
return false ;
if (power(a, n - 1 , n) != 1 )
return false ;
k--;
}
return true ;
}
public static void main(String[] args)
{
String s = "This is a python programming language" ;
String word;
String[] words = s.split( " " );
for (String w : words) {
if (isPrime(w.length()))
System.out.println(w);
}
}
}
|
Python3
import random
def power(a, n, p):
res = 1
a = a % p
while n > 0 :
if n & 1 :
res = (res * a) % p
n = n >> 1
a = (a * a) % p
return res
def gcd(a, b):
if a < b:
return gcd(b, a)
elif a % b = = 0 :
return b
else :
return gcd(b, a % b)
def isPrime(n):
k = 3
if n < = 1 or n = = 4 :
return False
if n < = 3 :
return True
while k > 0 :
a = random.randint( 2 , n - 2 )
if gcd(n, a) ! = 1 :
return False
if power(a, n - 1 , n) ! = 1 :
return False
k - = 1
return True
def main():
s = "This is a python programming language"
words = s.split()
for word in words:
if isPrime( len (word)):
print (word)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.IO;
class GFG
{
static int Power( int a, int n, int p)
{
int res = 1;
a = a % p;
while (n > 0)
{
if (n % 2 == 1)
res = (res * a) % p;
n = n >> 1;
a = (a * a) % p;
}
return res;
}
static int GCD( int a, int b)
{
if (a < b)
return GCD(b, a);
else if (a % b == 0)
return b;
else
return GCD(b, a % b);
}
static bool IsPrime( int n)
{
int k = 3;
if (n <= 1 || n == 4)
return false ;
if (n <= 3)
return true ;
while (k > 0)
{
Random random = new Random();
int a = random.Next(2, n - 1);
if (GCD(n, a) != 1)
return false ;
if (Power(a, n - 1, n) != 1)
return false ;
k--;
}
return true ;
}
static void Main()
{
string s = "This is a python programming language" ;
string [] words = s.Split( ' ' );
foreach ( string word in words)
{
if (IsPrime(word.Length))
Console.WriteLine(word);
}
}
}
|
Javascript
function power(a, n, p) {
let res = 1;
a = a % p;
while (n > 0) {
if (n & 1) {
res = (res * a) % p;
}
n = n >> 1;
a = (a * a) % p;
}
return res;
}
function gcd(a, b) {
if (a < b) {
return gcd(b, a);
} else if (a % b === 0) {
return b;
} else {
return gcd(b, a % b);
}
}
function isPrime(n) {
const k = 3;
if (n <= 1 || n === 4) {
return false ;
}
if (n <= 3) {
return true ;
}
let kCopy = k;
while (kCopy > 0) {
const a = Math.floor(Math.random() * (n - 3)) + 2;
if (gcd(n, a) !== 1) {
return false ;
}
if (power(a, n - 1, n) !== 1) {
return false ;
}
kCopy--;
}
return true ;
}
const s = "This is a python programming language" ;
const words = s.split( " " );
for (const word of words) {
if (isPrime(word.length)) {
console.log(word);
}
}
|
Time complexity: O(k Log n). Note that the power function takes O(Log n) time.
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...