Prime Number Program in Java - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Prime Number Program in Java

Prime Number Program in Java

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

  1. public class PrimeExample2{    
  2. static void checkPrime(int n){  
  3.   int i,m=0,flag=0;      
  4.   m=n/2;      
  5.   if(n==0||n==1){  
  6.    System.out.println(n+" is not prime number");      
  7.   }else{  
  8.    for(i=2;i<=m;i++){      
  9.     if(n%i==0){      
  10.      System.out.println(n+" is not prime number");      
  11.      flag=1;      
  12.      break;      
  13.     }      
  14.    }      
  15.    if(flag==0)  { System.out.println(n+" is prime number"); }  
  16.   }//end of else  
  17. }  
  18.  public static void main(String args[]){    
  19.   checkPrime(1);  
  20.   checkPrime(3);  
  21.   checkPrime(17);  
  22.   checkPrime(20);  
  23. }    
  24. }  

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.