-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem2.java
56 lines (45 loc) · 936 Bytes
/
Problem2.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package githubuploads;
import java.util.Scanner;
//#2 given a number N find all primes less than N;
public class Problem2 {
static void primeUpToN(int N)
{
if(N<=1)
{
System.out.println("No prime numbers");
return;
}
//boolean array to mark each number upto N+1
boolean[] mark = new boolean[N+1];
for(int i=2;i<N; i++)
{
mark[i]=true;
}
//start i from first prime number
for(int i=2;i*i<=N;i++)
{
//if a i is prime mark all its factors false
if(mark[i]==true)
{
for(int j=i*i;j<N;j+=i)
{
mark[j]=false;
}
}
}
//print prime numbers
for(int i=2;i<N;i++)
{
if(mark[i]==true)
{
System.out.print(i+" ");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
primeUpToN(N);
}
}