Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.