2016-06-28

Java program to check given number is prime number or not

Similar Questions:

  • Prime Numbers Java Example
  • Print prime numbers between 1 and given number using for loop

  • //check to see if the number is prime
  • boolean isPrime = true;
  •                         for(int j=2; j < 10 ; j++){
  •                                
  •                                 if(10 % j == 0){
  •                                         isPrime = false;
  •                                         break;
  •                                 }
  •                         }
  •                         // print the number
  •                         if(isPrime)
  •                                 System.out.print(i + " ");




Solution:

  1.  public class PrimeNumbersExample {
  2.  
  3.         public static void main(String[] args) {
  4.                
  5.                 //define limit
  6.                 int limit = 100;
  7.                
  8.                 System.out.println("Prime numbers between 1 and " + limit);
  9.                
  10.                 //loop through the numbers one by one
  11.                 for(int i=1; i < limit; i++){
  12.                        
  13.                         boolean isPrime = true;
  14.                        
  15.                         //check to see if the number is prime
  16.                         for(int j=2; j < i ; j++){
  17.                                
  18.                                 if(i % j == 0){
  19.                                         isPrime = false;
  20.                                         break;
  21.                                 }
  22.                         }
  23.                         // print the number
  24.                         if(isPrime)
  25.                                 System.out.print(i + " ");
  26.                 }
  27.         }
  28. }



No comments:

Post a Comment