java-to determine if a number is prime

Source: Internet
Author: User

1 ImportJava.util.Scanner;2 3 /**4  * @authorSchrödinger's Cat5 * Java Determines if a number is prime6  * 7 * Primes, also known as prime numbers, refers to the number of natural numbers greater than 1 that cannot be divisible by other natural numbers except 1 and itself .*/8  Public classPrimenumber {9      Public Static voidMain (string[] args) {TenScanner sc =NewScanner (system.in);//scanner, receiving console input information OneSystem.out.println ("Please enter an integer greater than 1:"); A          -         Try { -             intnum = Sc.nextint ();//the integer that receives the console input the              -             if(IsPrime (num)) {//Call the IsPrime () method -SYSTEM.OUT.PRINTLN (num + "is prime");//if the IsPrime () method returns True, the output is a prime number -                  +}Else { -                  +SYSTEM.OUT.PRINTLN (num + "not prime");//if the IsPrime () method returns FALSE, the output is not a prime number A             } at              -}Catch(Exception e) { -              -System.out.println ("Please enter an integer");//catch exception, if input illegal number, output exception -         } - sc.close (); in     } -      to     /** + * Used to determine if a number is a prime, if yes, returns TRUE, otherwise returns false -      * @paramthe value of a input the      * @returntrue False*/ *      $      Public Static BooleanIsPrime (inta) {Panax Notoginseng         BooleanFlag =true; -          the         if(A&LT;2) {//prime number not less than 2 +             return false; A}Else { the              for(inti = 2;i<=math.sqrt (a); i++) { +                 if(a% i = = 0) {//if it can be divisible, it means that it is not a prime, return false -Flag =false; $                      Break; $                 } -             } -         } the         returnFlag; -     }Wuyi}

java-to determine if a number is prime

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.