100 examples of classic Java programming exercises: Example 22: Determine whether a random integer is a prime number

Don't feel inferior, and improve your strength.
Who
is the best in the Internet industry? If the article can bring you energy, that's the best thing! Please believe in yourself, come
on o~

Java classic programming exercises, beginners can refer to learning

Insert picture description here
Click the link below to
summarize 100 examples of Java classic programming exercises

Title description:

Determine whether a random integer is a prime number

Problem-solving ideas:

开根号循环

Code:

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(isPrime(2));
    }
    public static boolean isPrime(int n){
    
    
        for(int i=2;i<=Math.sqrt(n);i++){
    
    
            if(n%i==0){
    
    
                return false;
            }
        }
        return true;
    }
}

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/113761589