Print Prime Numbers from 1 to 100 in Java

Print Prime Numbers from 1 to 100 in Java | Prime numbers are natural numbers that are divisible by only 1 and the number itself. In other words, prime numbers are positive integers greater than 1 with exactly two factors, 1 and the number itself. Also see:- Prime Number Program in Java

For example- 5 is a prime number because it has only two factors 1 and 5.

Similarly,
8 is not a prime number because it has more than 2 factors that are 1, 2, 4, and 8.

Note:- All negative numbers, 0 and 1 are not the prime numbers.

In this program, we will use the For Loop to print prime numbers from 1 to 100.

Program description:- Write a program to print prime numbers from 1 to 100 in java

public class PrimeNumberInRange {

  public static boolean isPrime(int number) {

    /* Negative numbers, 0 and 1 
     * are not a prime number
     * 
     * Even numbers (except 2) are
     * also not a prime number
     */
     if(number == 2) return true;
     else if(number<=1 || number%2==0)
         return false;

     // logic for remaining numbers
     for(int i=3; i<=Math.sqrt(number); i++) {
         if(number%i == 0) return false;
     }

     return true;
  }

  public static void main(String[] args) {

     // check in range
     System.out.println("Prime numbers from 1 to 100 are:");
     for(int i = 1; i<= 100; i++)
        if(isPrime(i)) 
           System.out.print( i + " ");
  }
}

Output:-

Prime numbers from 1 to 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *