Java judges prime numbers

Source: Internet
Author: User

Method 1:

Import java. util. collections;
Public class primenumber {
/* Use (INT) math. SQRT (n) to obtain the upper limit of the loop.
* The isprime () method is used to check whether the current number is a prime number.
*/
Public static Boolean isprime (INT num ){
Boolean prime = true;
Int Limit = (INT) math. SQRT (Num );
For (INT I = 2; I <= limit; I ++ ){
If (Num % I = 0 ){
Prime = false;
Break;
}
}
Return prime;
}
Public static void main (string [] ARGs ){
Wrote input = new partition (system. In );
System. Out. Print ("Enter the number you want to judge :");
Int n = input. nextint ();
If (isprime (N )){
System. Out. println (n + "is a prime number! ");
} Else {
System. Out. println (n + "is not a prime number! ");
}
}
}

Method 2:

Import java. util .*;
Public class primenumber1 {
// Refresh the maximum number of cycles once each cycle, for example, num = n/2. (assign the value of n/2 To num as the maximum number of cycles)
Public static void main (string [] ARGs ){
Wrote input = new partition (system. In );
Long number, I, sum;
String answer;
Boolean con = false;
Do {
System. Out. println ("enter an integer greater than 2 :");
Number = input. nextlong ();
Sum = number;
/* Determine the prime number */
For (I = 2; I <= sum; I ++ ){
If (Number % I = 0 ){
Con = true;
System. Out. println ("approx.:" + I );
Break;
} Else {
Sum = Number/I;
}
}
If (CON ){
System. Out. println (number + "Not Prime ");
} Else {
System. Out. println (number + "is a prime number ");
}
System. Out. println ("/n continue (y/n )");
Answer = input. Next ();
Con = false;
} While (answer. Equals ("Y "));
System. Out. println ("program ended !~ ");
}
}

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.