How to judge Java prime number

        Prime numbers (prime numbers), also known as prime numbers, are infinite. The code is very simple, through a loop to determine whether n is a prime number. Define a Java Boolean flag flag before the loop starts. In the loop, if n%j==0, then the number is not a prime number, and the flag assignment is true. At the end of the loop, use the flag to judge whether the number is a prime number. .

public static void isSuShu(int n){
boolean flag=false;
for(int j=2;j<=Math.sqrt(n);++j){
if(n%j==0)
flag=true; // Not primes 
}
if(flag==false)
System.out.println(n+" Prime number ");
else
System.out.println(n+" Not primes ");
}

Java finds the prime number between 1-100

Prime number definition:

        Prime numbers are also called prime numbers. A natural number greater than 1 that cannot be divisible by other natural numbers except 1 and itself is called a prime number; otherwise it is called a composite number.

Such as: 2, 3, 5, 7, 11...

1. Prime number example 1

public class PrimeNumber {
 public static void main(String[] args) {
  for(int i=2;i<=100;i++) {
   boolean flag=true;
   for(int j=2;j<i;j++) {
    if(i%j == 0) {
     flag=false;
     break;     
    }        
   }
   if(flag) {
    System.out.println("质数:i= "+i);   
   }
  }  
 }
}

2. Prime number example 2

//1-100之间的质数--------2
public class PrimeNumber {
 public static void main(String[] args) { 
        for(int i=2;i<=100;i++) {   
            for(int j=2;j<=i;j++) {
                if(i%j==0 && i!=j) {
                    break;     
                }
                if(j==i) {
                    System.out.println("质数:i= "+i);     
                }    
            }
        }
    }
}

3. Prime number example three

//1-100之间的质数--------3
public class PrimeNumber {
 public static void main(String[] args) {
        for(int i=2;i<=100;i++) {   
            int j=2;
            while(i%j != 0 ) {
                j++;     
            }
            if(j==i) {
                System.out.println("质数:i= "+i);         
            }
        }
    }
}

        Through the above introduction, I believe that everyone has some understanding of the method of judging prime numbers in Java. If you want to know more about it, you can click to follow. I hope it can be helpful to you.

Java learning video

Java basics:

Java300 episodes, Java must-have high-quality videos_Learn Java with hands-on diagrams, making learning a kind of enjoyment

Java project:

[Java game project] 1 hour to teach you how to make classic minesweeper games in Java language_Teach you how to develop games

[Java graduation project] OA office system project actual combat_OA employee management system project_java development

Guess you like

Origin blog.csdn.net/java_0000/article/details/125396405