Find Prime numbers in an array of ’n’ elements (command line arguments) Java

in #trending10 months ago

We have all learned the logic behind prime numbers, and now our task is to accept an array from the user via command-line arguments and find the prime numbers among those elements.

Let's see the output so that we can get fired up from the inside.

E:>java PNumbersInArray.java 3 4 5 6 7 8 9 10 12 13
3
5
7
13

As you can see we get the prime numbers from the above-mentioned array.

1_mxwAikbCRhpieXzPxkhz2w.webp

Java Code

class PNumbersInArray{
public static void main(String[] args){
for(String arg: args){
int num = Integer.parseInt(arg);
if(isPrime(num)>0){
System.out.println(num+" ");
}
}
}

public static int isPrime(int num){
if(num <=1){
return 0;
}
for(int i=2; i<=num; i++){
if(num % i == 0){
return 0;
}
}
return num;
}
}

How to get Input from Command line argument in Java

public static void main(String[] args){
for(String arg: args){
int num = Integer.parseInt(arg);

This piece of code is designed to receive input from command-line arguments. In the main method, we declare an array of String types named args.

Using a for-each loop, we iterate through the args elements one by one, assigning each element to the variable arg.

In the third line, each element is converted from a string to an integer.

How the isPrime() function is going to work?

public static int isPrime(int num){
if(num <=1){
return 0;
}
for(int i=2; i<=num; i++){
if(num % i == 0){
return 0;
}
}
return num;
}
}

In the condition ‘if (num ≤ 1),’ we check whether the number is less than or equal to one. If it is, we know that it will never be a prime number, so we return false.

for(int i=2; i<=num; i++){
if(num % i == 0){
return 0;
}
}

The above code is used to find prime numbers in the array elements.

Time Complexity O(n²)

Sort:  

Hello @surajjha. Welcome to Steemit.
I saw that you recently arrived on the platform.

On a blogging platform as big as Steemit, you run the risk of not moving forward and not getting the desired results if you do not follow the right path.

There are some basic rules to follow such as posting original content, spamming, plagiarism and AI are not allowed, images must be owned or sources must be cited.

Did you know that there is the Newcomers' Community on Steemit, which helps new users to achieve basic goals step by step in order to be ready for the Steemit ecosystem?

If you are interested in learning more, I recommend you take a look at: Newcomer Guidelines you will find a lot of information that will be useful.

You may also entering some competitions organised by the various communities that's a great way to gain more visibility and make yourself known on the platform.

Try to find the contest that suits you, visiting Contest Alerts: Active Contest List.

I hope I have been a little helpful and good luck with your blog.. 😊

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 57913.08
ETH 2452.28
USDT 1.00
SBD 2.36