Problem:
=============
Program for primality test in JAVA
What is primality test?
A primality test is an algorithm for determining whether an input number is prime.
Solution:
===========
import java.util.*;
public class PrimalityTest{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int i = scanner.nextInt();
if(i<0){
System.out.println("Please enter valid number ");
}
else {
System.out.println("is " + i + " prime number?" + isPrimeNumber(i));
}
}
public static boolean isPrimeNumber(int i){
boolean flag = false;
int counter = 0;
for(int j = 1; j <= i; j++){
if(i%j == 0 ){
counter++;
}
if(counter > 2){
break;
}
}
if(counter == 2){
flag = true;
}
return flag;
}
}
Second approach:
================
public static boolean isPrime(int N)
{
if (N < 2) return false;
for (int i = 2; i*i <= N; i++)
if (N % i == 0) return false;
return true;
}
Output:
=======
Enter a number
100
is 100 prime number?false
Enter a number
97
is 97 prime number?true
Enter a number
255
is 255 prime number?false
=============
Program for primality test in JAVA
What is primality test?
A primality test is an algorithm for determining whether an input number is prime.
Solution:
===========
import java.util.*;
public class PrimalityTest{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
int i = scanner.nextInt();
if(i<0){
System.out.println("Please enter valid number ");
}
else {
System.out.println("is " + i + " prime number?" + isPrimeNumber(i));
}
}
public static boolean isPrimeNumber(int i){
boolean flag = false;
int counter = 0;
for(int j = 1; j <= i; j++){
if(i%j == 0 ){
counter++;
}
if(counter > 2){
break;
}
}
if(counter == 2){
flag = true;
}
return flag;
}
}
Second approach:
================
public static boolean isPrime(int N)
{
if (N < 2) return false;
for (int i = 2; i*i <= N; i++)
if (N % i == 0) return false;
return true;
}
Output:
=======
Enter a number
100
is 100 prime number?false
Enter a number
97
is 97 prime number?true
Enter a number
255
is 255 prime number?false