Print prime numbers from 1 to 100 in java

In this program, we will print prime numbers from 1 to 100 in java.

A prime number is a number which has only two divisors 1 and itself. To check if the number is prime or not, we need to see if it has any other factors other than 1 or itself. If it has, then number is not prime else number is prime.


Algorithm

  • Iterate from 1 to 100.
  • In each iteration, check is number is prime or not.
  • If number is not divisible from 1 to sqrt(n) then number is not prime.
  • If number is prime, print it.

Here is java program to print prime numbers from 1 to 100.

package org.arpit.java2blog;

public class PrintPrimeNumberMain {

    public static void main(String[] args) {
        System.out.println("Prime numbers between 1 to 100 are:");
        for (int i = 1; i < 100; i++) {
            if(isPrimeNumber(i))
            {
                System.out.print(" "+i);
            }
        }
    }

    public static boolean isPrimeNumber(int number) {
           if (number <= 1) {
               return false;
           }
           for (int i = 2; i <= Math.sqrt(number); i++) {
               if (number % i == 0) {
                   return false;
               }
           }
           return true;
    }
}

When you will run above program, you will get below output:

Prime numbers between 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

That’s all about print prime numbers from 1 to 100 in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.