In this java program, we have one positive input and check whether the given number is prime or not.
Read what is Prime Number.
The simple case to check prime number we do,
if (number % 2 == 0){
print("Not prime");}
else {
print("is prime");}
But its complexity is much high if we use for loop. To decrease the complexity of the program read below question and solution.
Tic Tac Toe Python 3: The Standard Tic-Tac-Toe Game in Python 3
Java Program: Question
- You've to check whether a given number is prime or not.
- A number "t" as input representing a count of input numbers to be tested.
- Number "n" as input "t" number of times.
- For each input value of n, print "prime" if the number is prime and "not prime" otherwise.
Explanation and sample input
Input Format:
t
n
A number n
.. t number of times
Output Format:
prime
not prime
not prime
.. t number of times
Constraints:
1 <= t <= 10000
2 <= n < 10^9
Sample Input
5
19
21
33
37
121
Sample Output
prime
not prime
not prime
prime
not prime
Java Program:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
for(int i=0;i<t;i++){
int n = scn.nextInt();
int count = 0;
for(int div=2;div*div<=n; div++){
if (n % div == 0){
count++;
break;
}
}
if (count == 0){
System.out.println("prime");
}
else{
System.out.println("not prime");
}
}
}
Explanation:
In the first take number of test case t from the user, then start the for loop from 0 to t and take a positive integer n as input. Initialize the count variable from 0, and then again start the for loop from 0 to root(n) and then check the given number is prime or not prime using the if statement (if n % div is equal to 0 then increment the count variable of + 1 and terminate the for loop using break statement) and in the last if count variable is equal to 0 then print "prime" else "not prime".
Comments
Post a Comment
Thanks for the comment.