In: Computer Science
Java program
Prime Numbers
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Write a java program which reads a list of N integers and prints the number of prime numbers in the list.
Input: The first line contains an integer N, the number of elements in the list.
N numbers are given in the following lines.
Output: Print the number of prime numbers in the given list.
Constraints:
1 ≤ N ≤ 10000
2 ≤ an element of the list ≤ 108
Sample Input 1
5 2 3 4 5 6
Sample Output 1
3
Sample Input 2
11 7 8 9 10 11 12 13 14 15 16 17
Sample Output 2
4
Solution for the given question are as follows -
Code :
import java.util.Scanner;
public class Main
{
// check for duplicate element
public static boolean checkDuplicate(int a[] , int n) {
int c = 0;
for(int i = 0; i < a.length; i++)
{
if (a[i] == n) {
c++;
}
}
if (c == 1) {
return false;
}
return true;
}
public static void main(String[] args)
{
// local variable declaration
int n ,count = 0;
boolean flag = false;
Scanner s = new Scanner(System.in);
// get input from user
System.out.print("How many elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
// check duplicate elements
boolean duplicate = checkDuplicate(a,a[i]);
if (duplicate) {
continue;
}
// check element is prime or not
for(int j = 2; j <= a[i]/2; ++j)
{
if(a[i] % j == 0)
{
flag = true;
break;
}
}
// increment the prime count
if (!flag) {
count ++ ;
}
flag = false;
}
// print the count
System.out.println("Total Prime Numbers:"+count);
}
}
Code Screen Shot :
Output :
1)
2)