Java determines whether a number is prime [goto]

Source: Internet
Author: User
Tags goto

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

Import Java.util.Scanner;

prime number, also known as Prime , refers to the number of natural numbers greater than 1 , except 1 and this integer itself, cannot be divisible by other natural numbers

public class Primenumber {

public static void Main (string[] args) {

Scanner scan = new Scanner (system.in);// scanner, receiving console input information

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

try {

int num = Scan.nextint ();// Remove information from console input

if (IsPrime (num)) {// call 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 (" Please enter an integer ");// Catch an exception, if the input is not an integer, the output exception

}

}

/**

* <pre>

* used to determine if a number is a prime, if it is prime, returns true, otherwise false

* </pre>

*

* @param a

* the value entered

* @return True,false

*/

public static Boolean isprime (int a) {

Boolean flag = true;

if (a < 2) {// primes not less than 2

return false;

} else {

for (int i = 2; I <= math.sqrt (a); i++) {

If (a% i = = 0) {// if divisible, the description is not a prime, return false

Flag = false;

break;// Jump out of the loop

}

}

}

return flag;

}

}

Java determines whether a number is prime [goto]

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.