Question
Print prime number in an (array in Java/ list in Python).
Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.
Enter size of list:10
Enter elements in list:
1:10
2:13
3:14
4:-10
5:-13
6:1
7:98
8:23
9:24
10:2
Elements entered in given List:
[10, 13, 14, -10, -13, 1, 98, 23, 24, 2]
Prime numbers in given list:
13 23 2
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class PrimeNumberInGivenArray
{
public static void main(String args[])
{
/* Initialize array */
int [] arr;
int n=0,i=0,j=0;
boolean flag=true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array:");
n = sc.nextInt();
arr=new int[n];
System.out.println("Enter numbers in array:");
for(i=0;i< n;i++)
{
System.out.print((i+1)+":");
arr[i]=sc.nextInt();
}
System.out.println("Elements Entered in given array:");
for(i=0;i< n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("prime Elements in an array:");
for(i=0;i< n;i++)
{
flag=true;
if(arr[i]>1)
{
for(j=2;j< arr[i];j++)
{
/*Checking if number is divisible by j.*/
if(arr[i]%j==0)
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.print(arr[i]+" ");
}
}
}
}
}
Python
li=[]
size=int(input("Enter size of list:"))
print("Enter elements in list:")
for i in range(0,size):
print((i+1),end=":")
li.append(int(input()))
print("Elements entered in given List:")
print(li)
print("Prime numbers in given list:")
for number in li:
isPrimeNumber=True
"""
As number less than 1 are not prime numbers
so we will only check number greater than 1
"""
if(number>1):
for i in range(2,number):
# Checking if the given number is divisible
# by any other number expect 1 and itself
# If it is then it's not a prime number
if(number%i==0):
isPrimeNumber=False
break
if(isPrimeNumber==True):
print(number,end=" ")