Java determines whether a number is a prime number, and java Prime Number

Source: Internet
Author: User

Java determines whether a number is a prime number [conversion], a java Prime Number

Http://blog.csdn.net/lwcumt/article/details/8027586

Import java. util. collections;

// Prime number refers to a number in a natural number greater than 1, which cannot be divisible by other natural numbers except the integer 1 and itself.

Public class PrimeNumber {

Public static void main (String [] args ){

Scanner scan = new Scanner (System. in); // The Scanner receives information from the console

System. out. print ("enter an integer :");

Try {

Int num = scan. nextInt (); // retrieves information entered on the console

If (isPrime (num) {// call the isPrime () method

System. out. println (num + "is a prime number! "); // If the isPrime () method returns true, the output is a prime number.

} Else {

System. out. println (num + "is not a prime number! "); // If the isPrime () method returns false, the output is not a prime number.

}

} Catch (Exception e ){

System. out. println ("enter an integer"); // catch an exception. If the input is not an integer, the output is abnormal.

}

}

/**

* <Pre>

* Used to determine whether a number is a prime number. If it is a prime number, true is returned; otherwise, false is returned.

* </Pre>

*

* @ Param

* Input value

* @ Return true and false

*/

Public static boolean isPrime (int ){

Boolean flag = true;

If (a <2) {// The prime number is not less than 2

Return false;

} Else {

For (int I = 2; I <= Math. sqrt (a); I ++ ){

If (a % I = 0) {// if it can be divisible, it indicates it is not a prime number, and false is returned.

Flag = false;

Break; // skip Loop

}

}

}

Return flag;

}

}

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.