# 9.7 Mathematics and Probability (vii)--check if n can be divisible by prime number

Source: Internet
Author: User

/**
* 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;}} `

9.7 Mathematics and Probability (vii)--check if n can be divisible by prime number

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.