Prime Number Program in Java
Prime number in Java: Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.
public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Prime Number Program using Method in Java
- public class PrimeExample2{
- static void checkPrime(int n){
- int i,m=0,flag=0;
- m=n/2;
- if(n==0||n==1){
- System.out.println(n+" is not prime number");
- }else{
- for(i=2;i<=m;i++){
- if(n%i==0){
- System.out.println(n+" is not prime number");
- flag=1;
- break;
- }
- }
- if(flag==0) { System.out.println(n+" is prime number"); }
- }//end of else
- }
- public static void main(String args[]){
- checkPrime(1);
- checkPrime(3);
- checkPrime(17);
- checkPrime(20);
- }
- }
0 comments:
Post a Comment