/**
* Function: Check whether n can be divisible by prime number.
*/
/** * Generates prime sequence: Eratosthenes Sieve method * Principle: Excludes all non-prime numbers that may be divisible by prime numbers. * Idea: List all the numbers up to Max. * 1) Cross out all numbers that may be divisible by 2 (2 reserved). * 2) Find the next prime number (that is, the next not to be crossed out) and cross out all the numbers that can be divisible by it. * 3) finally get a sequence of primes between 2 and Max. * Can be optimized to: just put the odd number into the array, the space can be halved. * @param max * @return */public static boolean[] sieveoferatosthenes (int max) {boolean[] flags=new boolean[max+1];//starting from 0, total Max+1 bit. It is convenient for the index of the element to correspond to the number int count=0;init (flags), or//to set the flags except 0, 1 elements except for all elements of Trueint prime=2;while (Prime<=max) {// Draw out the remaining prime multiples of the number Crossoff (flags,prime);//Find the next bit true value Prime=getnextprime (flags,prime); if (prime>=flags.length) break;} return to the flags;} Draw off the number of the remaining prime multiples public static void Crossoff (boolean[] flags,int prime) {/** * to draw out the remaining prime multiples, starting with prime*prime, as if k* Prime and K<prime, * This value is already crossed out in previous iterations. */for (int i=prime*prime;i<flags.length;i+=prime) {if (i%prime==0) Flags[i]=false;}} Find the next bit true value public static int Getnextprime (boolean[] flags,int prime) {int Next=prime+1;while (next<flags.length &&!flags[next]) {next++;} return next;} public static void Init (boolean[] flags) {for (int i=0;i<flags.length;i++) {flags[i]=true;}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.7 Mathematics and Probability (vii)--check if n can be divisible by prime number