Below Simple program
Write a program that repeatedly prompts the user to enter a positive integer > 1. The program should then take this integer and determine whether it is prime. (A prime integer is evenly divisible only by itself and 1.) Then display whether the integer is prime or composite (not prime). If the user enters 0, then exit from the program. Hint: Use a for loop and the mod function
package com.prime;
import java.util.Scanner;
public class PrimeTest {
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
boolean value=false;
// while ()
int number= 2;
if(number==0)
{
System.exit(1);
}
//System.out.println("Please Enter Number");
while (number >0)
{
System.out.println("enter a positive integer > 1 : ");
number = sc.nextInt();
if(number==0)
{
System.exit(1);
}
value= TestPrimeNumber(number);
if(value=true)
{
System.out.println("Prime Number");
}
else
{
System.out.println("Not Prime Number");
}
}
}
private static boolean TestPrimeNumber(int n)
{
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
}
Write a program that repeatedly prompts the user to enter a positive integer > 1. The program should then take this integer and determine whether it is prime. (A prime integer is evenly divisible only by itself and 1.) Then display whether the integer is prime or composite (not prime). If the user enters 0, then exit from the program. Hint: Use a for loop and the mod function
package com.prime;
import java.util.Scanner;
public class PrimeTest {
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
boolean value=false;
// while ()
int number= 2;
if(number==0)
{
System.exit(1);
}
//System.out.println("Please Enter Number");
while (number >0)
{
System.out.println("enter a positive integer > 1 : ");
number = sc.nextInt();
if(number==0)
{
System.exit(1);
}
value= TestPrimeNumber(number);
if(value=true)
{
System.out.println("Prime Number");
}
else
{
System.out.println("Not Prime Number");
}
}
}
private static boolean TestPrimeNumber(int n)
{
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
}