Pages

Java determine prime number


Complete source code below will show you, how to create a simple java program that will determine an input number is a prime number or not. This program will run through command prompt.

********************************************************
COMPLETE SOURCE CODE FOR : JavaDeterminePrimeNumber.java
********************************************************


import java.util.Scanner;

public class JavaDeterminePrimeNumber
{
public boolean isPrime(int a)
{
boolean temp=true;
if(a==1)
{
return false;
}
for(int i=2;i<=a;i++)
{
if(i!=1&&i!=a)
{
int tempResult=a%i;
if(tempResult==0)
{
temp=false;
}
}
}
return temp;
}

public static void main(String[]args)
{
JavaDeterminePrimeNumber myTest=new JavaDeterminePrimeNumber();
Scanner s=new Scanner(System.in);
System.out.println("Enter an int value");
int response = s.nextInt();
boolean result=myTest.isPrime(response);

if(result==true)
{
System.out.println("This is a prime number");
}
else
{
System.out.println("This is not a prime number");
}
}
}


********************************************************
JUST COMPILE AND EXECUTE IT
********************************************************
Related Posts Plugin for WordPress, Blogger...