Print Words with Prime length from a Sentence


In this problem, we need to show all words of the string having the prime length. The logical part of the problem is getting the words from the string and checking whether its length is prime.

We can check whether the length of the number is divisible by any number to ensure whether it is a prime number. Also, we will use the sieve of Eratosthenes and the wheel factorization algorithm to check whether the word length is a prime number.

Problem statement − We have given a string alpha, and we need to print all words of the prime length.

Sample Example

Input: alpha = "Welcome to the tutorialspoin";
Output: Welcome, to, the, tutorialspoin,

Explanation

  • The length of 'welcome' is 7, which is prime.

  • The length of 'to' is 2 and 'the' is 3, which are also prime.

  • The length of the 'tutorialspoin' is 13, prime number.

Sample Example

Input: alpha = alpha = "Python java javascript"
Output: “”

Explanation

The string doesn't contain any word of prime length. So, it prints the empty string.

Sample Example

Input: alpha = "I am a good person";
Output: am

Explanation

It prints all words having a prime length.

Approach 1

This is the naïve approach to solving the problem. We will take each word of the string and check whether its length is prime. We will use the loop to check if the number is divisible by any number between 2 to sqrt(num). If yes, the number is a non-prime number. Otherwise, the number is a prime number.

Algorithm

  • Step 1 − Append the space at the end of the string to handle the last word, and define the 'temp' string to store the word.

  • Step 2 − Start traversing the string. If the current character is space, follow the below steps. Otherwise, append the character to the 'temp' string.

  • Step 3 − Execute the checkForPrime() function to check whether the size of the word is prime.

  • Step 3.1 − In the checkForPrime() function, if num is 2, return true. Also, if the number is negative, return false.

  • Step 3.2 − Make iterations from 2 to sqrt(num) to check if the number is divisible by any integer. If yes, return true.

  • Step 4 − Print the word if checkForPrime() function returns true.

Example

#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>

bool checkForPrime(int num) {
   if (num == 2)
      return true;
   if (num > 1) {
      // Check if the number is divisible by any number
      for (int p = 2; p < sqrt(num) + 1; p++) {
         if (num % p == 0) {
            return false;
         }
      }
      // When a number is not divisible by any number
      return true;
   } else {
      // When a number is negative
      return false;
   }
}

void findWords(char *alpha) {
   char *token = strtok(alpha, " ");
   // Traverse the string to get words
   while (token != NULL) {
      // If the size of a word is prime
      if (checkForPrime(strlen(token))) {
         printf("%s, ", token);
      }
      token = strtok(NULL, " ");
   }
}
int main() {
   char alpha[] = "Welcome to the tutorialspoin";
   printf("The words with prime length are: - ");
   findWords(alpha);
   printf("\n");
   return 0;
}

Output

The words with prime length are: - Welcome, to, the, tutorialspoin, 
#include <bits/stdc++.h>
using namespace std;

bool checkForPrime(int num) {
   if (num == 2)
      return true;
   if (num > 1) {
      // Check if the number is divisible by any number
      for (int p = 2; p < sqrt(num) + 1; p++) {
         if (num % p == 0) {
            return false;
         }
      }
      // When a number is not divisible by any number
      return true;
   } else {
      // When a number is negative
      return false;
   }
}
void findWords(string &alpha) {
   alpha += ' ';
   string temp;
   // Traverse the string to get words
   for (int p = 0; p < alpha.length(); p++) {
      if (alpha[p] == ' ') {
         // If the size of a word is prime
         if (checkForPrime(temp.size())) {
            cout << temp << ", ";
         }
         temp = "";
      } else {
         temp += alpha[p];
      }
   }
}
int main() {
   string alpha = "Welcome to the tutorialspoin";
   cout << " The words with the prime length are : - ";
   findWords(alpha);
   return 0;
}

Output

The words with the prime length are : - Welcome, to, the, tutorialspoin,
import java.util.ArrayList;

public class PrimeWordFinder {
   static boolean checkForPrime(int num) {
      if (num == 2)
         return true;
      if (num > 1) {
         // Check if the number is divisible by any number
         for (int p = 2; p < Math.sqrt(num) + 1; p++) {
            if (num % p == 0) {
               return false;
            }
         }
         // When a number is not divisible by any number
         return true;
      } else {
         // When a number is negative
         return false;
      }
   }

   static void findWords(String alpha) {
      String[] words = alpha.split(" ");
      // Traverse the array of words
      for (String word : words) {
         // If the size of a word is prime
         if (checkForPrime(word.length())) {
            System.out.print(word + ", ");
         }
      }
   }

   public static void main(String[] args) {
      String alpha = "Welcome to the tutorialspoin";
      System.out.print("The words with prime length are: - ");
      findWords(alpha);
      System.out.println();
   }
}

Output

The words with prime length are: - Welcome, to, the, tutorialspoin, 
import math

def checkForPrime(num):
   if num == 2:
      return True
   if num > 1:
      # Check if the number is divisible by any number
      for p in range(2, int(math.sqrt(num)) + 1):
         if num % p == 0:
            return False
      # When a number is not divisible by any number
      return True
   else:
      # When a number is negative
      return False

def findWords(alpha):
   words = alpha.split()
   # Traverse the list of words
   for word in words:
      # If the size of a word is prime
      if checkForPrime(len(word)):
         print(word + ", ", end="")

if __name__ == "__main__":
   alpha = "Welcome to the tutorialspoin"
   print("The words with prime length are: - ", end="")
   findWords(alpha)
   print()

Output

The words with prime length are: - Welcome, to, the, tutorialspoin, 

Time complexity − O(N*N), where O(N) is for traversing the string, and O(N) is to check whether the string length is prime.

Space complexity − O(N) to store words in the temp string.

Approach 2

This approach uses the sieve of Eratosthenes algorithm to find all prime numbers in the range of 0 to string length. So, we can check whether word length is prime from previously calculated results.

Algorithm

  • Step 1 - Define the 'primeNumber' set to store all prime numbers in the range 0 to string length. Execute the sieveAlgorithm() function to initialize the 'primeNumber' set.

  • Step 1.1 - In the sieveAlgorithm() function, define the 'isPrime' Boolean array of length str_len + 1, and initialize all elements with true.

  • Step 1.2 - Make iterations from 2 to sqrt(num). If isPrime[p] is true, make all its multiple non-prime by updating array value to false.

  • Step 1.3 - Insert all prime numbers in the set ranging from 0 to string length.

  • Step 2 - Use the istringstream to get the stream of the string and take each word from that.

  • Step 3 - If the set contains the length of the word, print the word.

Example

#include <stdio.h>
#include <string.h> // Include for memset and strlen
#include <stdlib.h>
#include <stdbool.h>

void sieveAlgorithm(int strLen, int *pmNumbers) {
   bool isPrime[strLen + 1];
   memset(isPrime, true, sizeof(isPrime));
   for (int p = 2; p * p <= strLen; p++) {
      if (isPrime[p] == true) {
         // Change the value of a multiple of p
         for (int q = p * 2; q <= strLen; q += p)
            isPrime[q] = false;
      }
   }
   // Add prime numbers to the array
   int index = 0;
   for (int p = 2; p <= strLen; p++)
      if (isPrime[p])
         pmNumbers[index++] = p;
}

void findWords(char *alpha) {
   int pmNumbers[100]; // Assuming a maximum of 100 prime numbers
   sieveAlgorithm(strlen(alpha), pmNumbers);
   char *token = strtok(alpha, " ");
   // Check the length of each word
   while (token != NULL) {
      int wordLength = strlen(token);
      for (int i = 0; pmNumbers[i] != 0; i++) {
         if (pmNumbers[i] == wordLength) {
            printf("%s, ", token);
            break;
         }
      }
      token = strtok(NULL, " ");
   }
}

int main() {
   char alpha[] = "Welcome to the tutorialspoint";
   printf("The words with prime lengths are: ");
   findWords(alpha);
   return 0;
}

Output

The words with prime lengths are: Welcome, to, the, 
#include <bits/stdc++.h>
using namespace std;

void sieveAlgorithm(int strLen, set<int> &pmNumbers) {
   bool isPrime[strLen + 1];
   memset(isPrime, true, sizeof(isPrime));
   for (int p = 2; p * p <= strLen; p++) {
      if (isPrime[p] == true) {
         // Change the value of a multiple of p
         for (int q = p * 2; q <= strLen; q += p)
            isPrime[q] = false;
      }
   }
   // Add prime numbers in the set
   for (int p = 2; p <= strLen; p++)
      if (isPrime[p])
         pmNumbers.insert(p);
}
void findWords(string &alpha) {
   set<int> pmNumbers;
   sieveAlgorithm(alpha.size(), pmNumbers);
   istringstream stream(alpha);
   string temp;
   // Check the length of each word
   while (stream >> temp) {
      if (pmNumbers.find(temp.size()) != pmNumbers.end()) {
         cout << temp << ", ";
      }
   }
}
int main() {
   string alpha = "Welcome to the tutorialspoint";
   cout << " The words with the prime length are: ";
   findWords(alpha);
   return 0;
}

Output

The words with the prime length are: Welcome, to, the, 
import java.util.*;

public class PrimeLengthWords {
    
   public static void sieveAlgorithm(int strLen, Set<Integer> pmNumbers) {
      boolean[] isPrime = new boolean[strLen + 1];
      Arrays.fill(isPrime, true);
       
      for (int p = 2; p * p <= strLen; p++) {
         if (isPrime[p]) {
            // Change the value of a multiple of p
            for (int q = p * 2; q <= strLen; q += p)
               isPrime[q] = false;
         }
      }
       
      // Add prime numbers to the set
      for (int p = 2; p <= strLen; p++) {
         if (isPrime[p])
            pmNumbers.add(p);
      }
   }
    
   public static void findWords(String alpha) {
      Set<Integer> pmNumbers = new HashSet<>();
      sieveAlgorithm(alpha.length(), pmNumbers);
      String[] words = alpha.split(" ");
      
      // Check the length of each word
      List<String> primeLengthWords = new ArrayList<>();
      for (String word : words) {
         if (pmNumbers.contains(word.length())) {
            primeLengthWords.add(word);
         }
      }
      System.out.println(String.join(", ", primeLengthWords));
   }
    
   public static void main(String[] args) {
      String alpha = "Welcome to the tutorialspoint";
      System.out.print("The words with prime lengths are: ");
      findWords(alpha);
   }
}	

Output

The words with prime lengths are: Welcome, to, the
import math

def sieve_algorithm(str_len):
   is_prime = [True] * (str_len + 1)
   pm_numbers = []
   
   for p in range(2, int(math.sqrt(str_len)) + 1):
      if is_prime[p]:
         for q in range(p * 2, str_len + 1, p):
            is_prime[q] = False

   for p in range(2, str_len + 1):
      if is_prime[p]:
         pm_numbers.append(p)
   
   return pm_numbers

def find_words(alpha):
   pm_numbers = sieve_algorithm(len(alpha))
   words = alpha.split()
   result = []
    
   for word in words:
      if len(word) in pm_numbers:
         result.append(word)
    
   print("The words with the prime length are:", ", ".join(result))

if __name__ == "__main__":
   alpha = "Welcome to the tutorialspoint"
   find_words(alpha)

Output

The words with the prime length are: Welcome, to, the

Time complexity − O(NLogN) for finding prime numbers.

Space complexity − O(N) to store prime numbers in the set.

Approach 3

This approach uses the wheel factorization technique to check whether the given number is a prime number.

Algorithm

  • Step 1 − Start traversing the string. Check whether the word length is prime if the current character is space. Otherwise, append the current character to the temp string.

  • Step 2 − In the checkForPrime() function, if the number is less than 1, return true.

  • Step 3 − If the number is 2 or 3, return true.

  • Step 4 − If the number is divisible by 2 or 3, return true.

  • Step 5 − Start making iterations from 5 and sqrt(num) in steps of 6.

  • Step 6 − if the number is divisible by p or p + 2, return false.

  • Step 7 − At last, return false.

  • Step 8 − Print the word if the checkForPrime() function returns true.

Example

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// Function to check if a number is prime
bool checkForPrime(int num) {
   if (num <= 1) {
      return false;
   } else if (num == 2 || num == 3) {
      return true;
   } else if (num % 2 == 0 || num % 3 == 0) {
      return false;
   } else {
      // Check divisibility by numbers of the form 6k +/- 1
      for (int p = 5; p * p <= num; p += 6) {
         if (num % p == 0 || num % (p + 2) == 0)
            return false;
      }
   }
   return true;
}

// Function to find words with prime lengths in a string
void findWords(char *alpha) {
   char temp[100]; // Assuming a maximum word length of 100
   int tempIndex = 0;
   
   for (int p = 0; alpha[p] != '\0'; p++) {
      if (alpha[p] == ' ') {
         temp[tempIndex] = '\0'; // Null-terminate the temp string
         tempIndex = 0; // Reset the index
         
         // If the size of the word is prime, print it
         if (checkForPrime(strlen(temp))) {
            printf("%s, ", temp);
         }
      } else {
         temp[tempIndex++] = alpha[p]; // Add character to temp
      }
   }
}

int main() {
   char alpha[] = "Welcome to the tutorialspoint";
   printf("The words with prime lengths are: ");
   findWords(alpha);
   return 0;
}

Output

The words with prime lengths are: Welcome, to, the, 
#include <bits/stdc++.h>
using namespace std;

bool checkForPrime(int num){
   // When a number is less than 1
   if (num <= 1) {
      return false;
   } else if (num == 2 || num == 3) {
      return true;
   } else if (num % 2 == 0 || num % 3 == 0) {
      // Check whether the number is divisible by 2 or 3
      return false;
   } else {
      // Check whether the number is divisible by a multiple of 5 and 7
      for (int p = 5; p * p <= num; p += 6) {
         if (num % p == 0 || num % (p + 2) == 0)
            return false;
      }
   }
   return true;
}
void findWords(string &alpha) {
   alpha += ' ';
   string temp;
   // Traverse the string to get words
   for (int p = 0; p < alpha.length(); p++) {
      if (alpha[p] == ' ') {
         // If the size of the word is prime
         if (checkForPrime(temp.size())) {
            cout << temp << ", ";
         }
         temp = "";
      } else {
         temp += alpha[p];
      }
   }
}
int main() {
   string alpha = "Welcome to the tutorialspoint";
   cout << " The words with the prime length are: ";
   findWords(alpha);
   return 0;
}

Output

The words with the prime length are:  Welcome, to, the,
public class PrimeLengthWords {
    
   // Function to check if a number is prime
   public static boolean checkForPrime(int num) {
      if (num <= 1) {
         return false;
      } else if (num == 2 || num == 3) {
         return true;
      } else if (num % 2 == 0 || num % 3 == 0) {
         return false;
      } else {
         // Check divisibility by numbers of the form 6k +/- 1
         for (int p = 5; p * p <= num; p += 6) {
            if (num % p == 0 || num % (p + 2) == 0) {
               return false;
            }
         }
      }
      return true;
   }
    
   // Function to find words with prime lengths in a string
   public static void findWords(String alpha) {
      alpha += ' ';  // Add a space to handle the last word
      String temp = "";
      String[] words = alpha.split(" ");
      System.out.print("The words with prime lengths are: ");
      for (String word : words) {
         // If the size of the word is prime, print it
         if (checkForPrime(word.length())) {
            System.out.print(word + ", ");
         }
      }
   }
    
   public static void main(String[] args) {
      String alpha = "Welcome to the tutorialspoint";
      findWords(alpha);
   }
}

Output

The words with prime lengths are: Welcome, to, the, 
# Function to check if a number is prime
def check_for_prime(num):
   if num <= 1:
      return False
   elif num == 2 or num == 3:
      return True
   elif num % 2 == 0 or num % 3 == 0:
      return False
   else:
      # Check divisibility by numbers of the form 6k +/- 1
      p = 5
      while p * p <= num:
         if num % p == 0 or num % (p + 2) == 0:
            return False
         p += 6
   return True

# Function to find words with prime lengths in a string
def find_words(alpha):
   alpha += ' '  # Add a space to handle the last word
   temp = ''
   result = []
   for char in alpha:
      if char == ' ':
         # If the size of the word is prime, add it to the result
         if check_for_prime(len(temp)):
            result.append(temp)
         temp = ''
      else:
         temp += char
   print("The words with prime lengths are:", ", ".join(result))

if __name__ == "__main__":
   alpha = "Welcome to the tutorialspoint"
   print("The words with prime lengths are:", end=' ')
   find_words(alpha)

Output

The words with prime lengths are: Welcome, to, the

Updated on: 27-Oct-2023

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements