Tuesday, 5 September 2017

java - is a prime number ?

 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.stream.IntStream;

public class _Math {
    
    static int[] prime_generator(int size){
        // return IntStream.iterate(2, a -> a+1).filter(InterviewQuestions::is_prime_method_1).limit(size).toArray();

        int array[] = new int[size];
        if(size == 0)
            return array;

        array[0] = 2;

        if(size == 1)
            return array;

        array[1] = 3;

        if(size == 2)
            return array;

        // all other than 2, 3 can is in form of 6k ± 1
        for (int i = 0, index = 2; index < array.length; i++) {
            int n1 = 6 * i;

            if(is_prime(n1 - 1))
                array[index++] = n1 - 1;
            if(is_prime(n1 + 1))
                array[index++] = n1 + 1;
        }

        return array;
    } 

    /**
     *  https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
     * @param upto
     * @return
     */
    static int[] prime_generator_by_sieve_of_eratosthenes(int upto){
        int[] base = IntStream.range(0, upto+1).toArray();
        base[0] = base[1] = 0;

        for (int i = 2; i < base.length; i++) {
            if(base[i] == 0)
                continue;
            for (int j = 2; i*j < base.length; j++) {
                base[i*j] = 0;
            }
        }
        return IntStream.of(base).filter(i -> i != 0).toArray();
    } 

    /**
     *  https://en.wikipedia.org/wiki/Primality_test
     * @param num
     * @return
     */
    static boolean is_prime(int num){
        if(num < 2)
            return false;
        if(num == 2 || num == 3)
            return true;

        if(num%2 == 0)
            return false;

        // max number which is divide a number is its sqrt, after that is can only divided by itself
        int max = (int) Math.sqrt(num);
        for (int i = 3; i <= max; i+=2) 
            if(num%i == 0)
                return false;

        return true;
    }
}

styled using hilite.me

No comments:

Post a Comment