Problem statement:
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
Example:
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
Example:
Input : n =10
Output : 2 3 5 7
Input : n = 20
Output: 2 3 5 7 11 13 17 19
2 3 5 7
- public class PrimeNumberSeries {
- public static void main(String arg[]) {
- primeNumberSeries(10);
- }
- public static void primeNumberSeries(int n) {
- // Create a boolean array "prime[0..n]" and initialize all entries it as //true. A value in prime[i] will finally be false if i is Not a prime, else true
- boolean prime[] = new boolean[n + 1];
- for (int i = 0; i < n; i++) {
- prime[i] = true;
- }
- for (int p = 2; p * p <= n; p++) {
- if (prime[p] == true) {
- // update all multiple of p
- for (int i = p * 2; i <= n; i = i + p) {
- prime[i] = false;
- }
- }
- }
- // print all prime numbers
- for (int i = 2; i <= n; i++) {
- if (prime[i] == true) {
- System.out.print(i + " ");
- }
- }
- }
- }
2 3 5 7
No comments:
Post a Comment