Sunday, February 15, 2015

Sieve of Eratoshenes


A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

I want to find Prime number from 2, 3, .... To  N

First we need to make
new int [N];



like this ~ we visit all number of Array.

below is my code



 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
/**
  * 1== prime 
  * 
  * @return
  */
 public static int[] isPrimeFromSieve(int limit) {

  int[] val = new int[limit];

  for (int i = 2; i < val.length; i++) {
   if (val[i] == 0) {
    val[i] = 1;

    checkMultiple(i, val);
   }
  }

  return val;
 }
 
 private static void checkMultiple(int a, int[] val) {

  for (int i = 2; i < val.length; i++) {
   int num = a * i;

   if (num >= val.length) {
    return;
   }
   val[num] = 2;
  }
 }

No comments:

Post a Comment