Check whether given number is prime or not (using for loop in java )
import java.util.Scanner;
class Ashraf7
{
public static void main(String args[])
{
int i,num =0;
boolean flag = false;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number");
num= sc.nextInt();
for (i= 2; i<=num/2; i++)
{
if(num % i==0)
{
flag =true;
break;
}
}
if(!flag)
System.out.println("The number is prime number ");
else
System.out.println("The number is not prime number ");
}
class Ashraf7
{
public static void main(String args[])
{
int i,num =0;
boolean flag = false;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number");
num= sc.nextInt();
for (i= 2; i<=num/2; i++)
{
if(num % i==0)
{
flag =true;
break;
}
}
if(!flag)
System.out.println("The number is prime number ");
else
System.out.println("The number is not prime number ");
}
Check whether given number is prime or not (using while loop in java )
import java.util.Scanner;
class Ashraf7
{
public
static void
main(String args[])
{
int i=2,num =0;
boolean flag = false;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number");
num= sc.nextInt();
while ( i<=num/2)
{
i++;
if(num % i==0)
{
flag =true;
break;
}
}
if(!flag)
System.out.println("The number is prime number ");
else
System.out.println("The number is not prime number ");
}
}
class Ashraf7
{
public
static void
main(String args[])
{
int i=2,num =0;
boolean flag = false;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the number");
num= sc.nextInt();
while ( i<=num/2)
{
i++;
if(num % i==0)
{
flag =true;
break;
}
}
if(!flag)
System.out.println("The number is prime number ");
else
System.out.println("The number is not prime number ");
}
}
OUTPUT:
Tags
Java programming