Java determines that a number is prime (optimized)

Source: Internet
Author: User

Prime: A natural number that is greater than 1 and that can only be divisible by 1 and itself is called Prime.

We think that the computer determines whether a number is a prime process: for example 11

i=2

2*3 2*3 2*5

I=3

3*2 3*3

I=4

4*2

I=5

5*2

I=6 (over 11 in size)

6*2

Here, we can write a very simple procedure for the law of exhaustion.

int i=2;

while ((n%i!=0) &&i<n)

i++;

Obviously, the above method is inefficient.

We can find the law. When i=3, 3*3 is a critical value, which is I*i, which is i*i<n.

The code posted

Package Judgeprim;

public class Prime {public
static void judgeprime (int n) {
Boolean flag = false;
int i = 2;
while ((n% i!= 0) && i * I < n) {
	i + +;
	
}
if (i * i > N) {
System.out.println ("is Prime");
}
else{
	System.out.println ("Non prime");
}
	public static void Main (String args[]) {
judgeprime (one);

}
}


Contact Us

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.