Prime String concept and program in Java - Explained

 

Prime Strings:

You must have heard about prime numbers. But have you ever thought about prime string? 

It's very simple and interesting. Here's the explanation:-

 In computer science, string is sequence of characters.Characters may be alphabets, numbers, punctuation, or special symbols.

So any word is a string. for example: "Hello" is a string.

Now, what is prime string? A string which cannot be constructed by concatenating two or more than two(multiple) equal strings.

Let's have a string "Road" , when we divide "road" into two equal parts we get "ro" and "ad" which are not equal strings. Thus "road" is a prime string.

Now let's take a string "baba". By dividing this string into two equal parts we get "ba" and "ba" . Both these strings are equal. So it is not a prime string.

Here's a prime string program written in java. It also tells the first half and second half of a string and whether it is prime or not.

import java.util.Scanner;
class PrimeString
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to check whether it is prime or not?");
String s = input.next(); //Getting user input
int i,len = s.length(); //Find length of string
String s1 = ""; 
String s2 = "";
if((len % 2) != 0) //if length of string is odd then it would definitely be prime
System.out.println("The entered string is PRIME!");
else  //if string's length is even
{
for(i=0;i<len/2;i++)  //loop for seperating first half of string
s1 = s1 + (s.charAt(i));
for(i=len/2;i<len;i++)  //loop for seperating second half of string
s2 = s2 + (s.charAt(i));
if(s1.equals(s2))  //if both parts are equal then string is not prime
System.out.println("The entered string is not PRIME!");
else  //if they are different then string is prime
System.out.println("The entered string is PRIME!");
}
}
}

Output of Prime String program
Output of the above program


Thus a string whose two equal parts are not same is called a prime string.

Post a Comment

Previous Post Next Post